package com.lanyou.esb.web;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.rmi.NoSuchObjectException;
import java.text.Collator;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.Map.Entry;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import javax.wsdl.WSDLException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.keyvalue.MultiKey;
import org.apache.commons.collections4.map.MultiKeyMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.lanyou.cook.common.Constants;
import com.lanyou.cook.datadictionary.KettleJobScheduleCycleUnit;
import com.lanyou.cook.datadictionary.UserLogOpt;
import com.lanyou.cook.entity.domain.FieldSystem;
import com.lanyou.cook.entity.domain.ParamSetting;
import com.lanyou.cook.entity.domain.userManagement.User;
import com.lanyou.cook.paramsetting.ParamSettingReppository;
import com.lanyou.cook.repository.FieldSystemRepository;
import com.lanyou.cook.repository.userManagement.UserRepository;
import com.lanyou.cook.service.SendEmailService;
import com.lanyou.cook.service.UserLogService;
import com.lanyou.cook.service.security.UserSessionService;
import com.lanyou.cook.util.DateUtil;
import com.lanyou.cook.util.gson.GsonUtil;
import com.lanyou.cook.web.param.TreeNode;
import com.lanyou.esb.common.CommonUtils;
import com.lanyou.esb.datadictionary.AuditStatusType;
import com.lanyou.esb.datadictionary.FtpAccessType;
import com.lanyou.esb.datadictionary.FtpHostType;
import com.lanyou.esb.datadictionary.FtpScheduleUnit;
import com.lanyou.esb.datadictionary.FtpSourceFileHanderType;
import com.lanyou.esb.datadictionary.FtpTargetFileHanderType;
import com.lanyou.esb.datadictionary.IfParameterType;
import com.lanyou.esb.datadictionary.IfStatusType;
import com.lanyou.esb.datadictionary.IfType;
import com.lanyou.esb.datadictionary.ParameterType;
import com.lanyou.esb.datadictionary.ScheduleType;
import com.lanyou.esb.entity.DefinedBundle;
import com.lanyou.esb.entity.Ftp;
import com.lanyou.esb.entity.FtpServer;
import com.lanyou.esb.entity.Http;
import com.lanyou.esb.entity.IfParameter;
import com.lanyou.esb.entity.IfReqQuantity;
import com.lanyou.esb.entity.IfSchedule;
import com.lanyou.esb.exception.BundleActionException;
import com.lanyou.esb.exception.ServerMixException;
import com.lanyou.esb.exception.ServiceHandlerException;
import com.lanyou.esb.repository.DefinedBundleRepository;
import com.lanyou.esb.repository.FtpRepository;
import com.lanyou.esb.repository.HttpRepository;
import com.lanyou.esb.repository.IfParameterRepository;
import com.lanyou.esb.service.ServiceManagerService;
import com.lanyou.esb.service.WsdlMetaDataService;
import com.lanyou.esb.servicemix.bean.Bundle;
import com.lanyou.esb.servicemix.monitor.ESBServerFactory;
import com.lanyou.esb.servicemix.util.ConnetServerTest;
import com.lanyou.esb.servicemix.util.FtpRouteHandleUtil;
import com.lanyou.esb.util.CornExpressionUtil;
import com.lanyou.esb.util.FileUploadCilent;
import com.lanyou.esb.vo.FtpVo;
import com.lanyou.esb.vo.HttpVo;
import com.lanyou.esb.web.param.BaseServiceManagementParam;
import com.lanyou.esb.web.param.HttpInterfaceParam;
import com.lanyou.esb.web.serviceManagement.vo.InterfaceVo;
import com.sun.javafx.binding.StringFormatter;

/**
 * 服务管理控制层
 * @author ly-yangchenrui
 *
 */
@RestController
@RequestMapping(Constants.BASE_URL_API + "/https")
public class ServiceManagerController {

	@Autowired
	private HttpRepository httpRepository;
	@PersistenceContext
	private EntityManager entityManager;
	@Autowired
	UserSessionService userSessionService;
	@Autowired
	ServiceManagerService serviceManagerService;
	@Autowired
    private WsdlMetaDataService  wsdlMetaDataService;
	
	@Autowired
	private SendEmailService sendEmailService;
	
	@Autowired
	private FtpRepository ftpRepository;
	
	@Autowired
	private ParamSettingReppository paramSettingReppository;
	
	@Autowired
	private DefinedBundleRepository definedBundleRepository;
	
	@Autowired
	private FieldSystemRepository fieldSystemRepository;
	
	@Autowired
	private ResourceLoader resourceLoader;
	
	@Autowired
	private ESBServerFactory eSBServerFactory;
	
	@Autowired
	private UserLogService userLogService;
	
	@Autowired
	private IfParameterRepository ifParameterRepository;
	
	@Autowired
	private UserRepository userRepository;
	
	
	private static FastDateFormat fastDateFormat1 = FastDateFormat
			.getInstance(Constants.DATETIME_PATTERN_1);
	
	/**
	 * 
	 * @param param
	 * @param pageable
	 * @return
	 */
	@RequestMapping("/search/findByExample")
	public Page<Http> findByExample(HttpInterfaceParam param, Pageable pageable) {
		if (!param.isSelectAll() && !param.haveCondition()) {
			return new PageImpl<Http>(new ArrayList<>(0), pageable, 0);
		}
		Specification<Http> spec = new Specification<Http>() {
			@Override
			public Predicate toPredicate(Root<Http> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicatesList = new ArrayList<>();
				if (StringUtils.isNotBlank(param.getFieldName())) {
					predicatesList.add(
							cb.like(root.get("fieldSystem").get("field").get("id"), '%' + param.getFieldName() + '%'));
				}
				
				if (StringUtils.isNotBlank(param.getFieldSystemName())) {
					predicatesList
							.add(cb.like(root.get("fieldSystem").get("id"), '%' + param.getFieldSystemName() + '%'));
				}

				if (StringUtils.isNotBlank(param.getStatus())) {
					predicatesList.add(cb.like(root.get("status"), '%' + param.getStatus() + '%'));
				}

				if (StringUtils.isNotBlank(param.getAuditStatus())) {
					predicatesList.add(cb.like(root.get("auditStatus"), '%' + param.getAuditStatus() + '%'));
				}
				
				if (StringUtils.isNotBlank(param.getIsEnable())) {
					predicatesList.add(cb.like(root.get("isEnable"), '%' + param.getIsEnable() + '%'));
				}

				if (StringUtils.isNotBlank(param.getName())) {
					predicatesList.add(cb.like(root.get("name"), '%' + param.getName() + '%'));
				}
				if (StringUtils.isNotBlank(param.getId())) {
					predicatesList.add(cb.like(root.get("id"),  param.getId() ));
				}
				

				// 领域系统
				Path<String> pathOwnerFieldSystemId = root.get("fieldSystem").get("id");
				if (StringUtils.isNotBlank(param.getFieldSystemId())) {
					predicatesList.add(cb.equal(pathOwnerFieldSystemId, param.getFieldSystemId()));
				} else {
					// 默认查当前登录用户所管理的领域系统
					Collection<String> fieldSystemIds = userSessionService
							.findFieldSystemIdsOfCurrentAuthenticatedUserCanManage();
					if (!CollectionUtils.isEmpty(fieldSystemIds)) {
						predicatesList.add(pathOwnerFieldSystemId.in(fieldSystemIds));
					} else {
						predicatesList.add(cb.notEqual(cb.literal(1), 1));
					}
				}

				// 领域
				if (StringUtils.isNotBlank(param.getFieldId())) {
					predicatesList.add(cb.equal(root.get("fieldSystem").get("field").get("id"), param.getFieldId()));
				}

				// 纠正错误的时间参数
				DynaBean fixedDates = DateUtil.fixBeginTimeAndEndTime(param.getBeginOfCreateTime(),
						param.getEndOfCreateTime());
				Date fixedBeginTime = (Date) fixedDates.get("begin");
				Date fixedEndTime = (Date) fixedDates.get("end");

				Path<Date> pathDate = root.get("createTime");
				predicatesList.add(cb.or(cb.isNull(pathDate), cb.between(pathDate, fixedBeginTime, fixedEndTime)));

				query.where(predicatesList.toArray(new Predicate[predicatesList.size()]));
				return null;
			}
		};
		return httpRepository.findAll(spec, pageable);
	}

	
	
	@ResponseBody
	@RequestMapping(value = "/searchDuplic", produces = "application/json")
	public String DealDetectDuplic(){
		//拿到原始地址相同而且有接口参数的接口的重复接口集合
		List<Object[]> results = httpRepository.findAllResult();
		Map<String,List<String>> ne = new HashMap<>();
		Map<String,List<String>> ne2 = new HashMap<>();
		List<String> list = new ArrayList<>();
		List<String> list2 = new ArrayList<>();
		for(Object[] ob :results){
			int time = ifParameterRepository.findByHttp_idAndType(ob[1].toString(), "1").size();
			String priUrl = ob[0].toString();
			String id = ob[1].toString();
			if(ne2.put(priUrl, list)==null&&!(list2.contains(id))){
				for(Object[] obj :results){
					String priUrl2 = obj[0].toString();
					int time2 = ifParameterRepository.findByHttp_idAndType(obj[1].toString(), "1").size();
					String id2 = obj[1].toString();
					if(StringUtils.equals(priUrl,priUrl2)
							&&time==time2&&!(StringUtils.equals(id, id2))){
						//如果原始地址相同而且元素个数相同,放在一组
						List<String> res = ne.put(priUrl,list);
						if( res==null){
							res = new ArrayList<>();
							res.add(ob[1].toString());
							res.add(obj[1].toString());
							list2.add(ob[1].toString());
							list2.add(obj[1].toString());
							ne.put(priUrl,res);
							ne2.put(priUrl,res);
						}else{
							res.add(obj[1].toString());
							list2.add(obj[1].toString());
							ne.put(priUrl,res);
							ne2.put(priUrl,res);
						}
					}
				}
			}
		}
		int i = 0;
		Map<Integer,List<String>> map2 = new HashMap<>();
		for(Entry<String, List<String>> entry:ne.entrySet()){
			i=i+1;
			List<String> lis = entry.getValue();//lis是原始地址相同而且参数个数相同的一个集合
			List<String> listresult = new ArrayList<>();
			
			for(String li:lis){//lis是一个相同原始地址和相同接口数的接口集合,li是其中一个接口
				List<IfParameter> ifps = ifParameterRepository.findByHttp_idAndType(li,"1");//一个接口的参数集合
				List<String> listt = new ArrayList<>();//定义个list去一个接口的存放参数
				List<String> listt2 = new ArrayList<>();//定义个list存放已经比较的接口
				listt2.add(li);
				if(!(listresult.contains(li))){
					for(IfParameter param:ifps){//
						String name = param.getName();
						String type = param.getDataType();
						listt.add(name+type);
					}
					for(String li2:lis){
						if(!(listt2.contains(li2))){
							List<IfParameter> ifps2 = ifParameterRepository.findByHttp_idAndType(li2,"1");//一个接口的参数集合
							List<String> listt22= new ArrayList<>();//定义个list去一个接口的存放参数
							for(IfParameter param2:ifps2){//
								String name2 = param2.getName();
								String type2 = param2.getDataType();
								listt22.add(name2+type2);
							}
							int k=0;
							for(String str:listt22){
								if(listt.contains(str)){
									k++;
								}else{
									break;
								}
							}
							if(k==listt.size()){
								if(!(listresult.contains(li))){
									listresult.add(li);
								}
								if(!(listresult.contains(li2))){
									listresult.add(li2);
								}
							}
							
						}
					}
				}
				map2.put(i, listresult);
			}
		}
		JsonArray jo = new JsonArray();
		for(Entry<Integer, List<String>> entry:map2.entrySet()){
			List<String> lis = entry.getValue();
			JsonArray je = new JsonArray();
			for(String interfaceId:lis){
				JsonObject lis2 = new JsonObject();
				Http http = httpRepository.findOne(interfaceId);
				lis2.addProperty("interfaceName", http.getName());
				lis2.addProperty("interfaceId", http.getId());
				je.add(lis2);
			}
			jo.add(je);
		}
		
		return jo.toString();
	}
	
	/**
	 * 业务服务管理中根据查询条件获取所有的接口信息
	 * @param param 查询条件实体
	 * @param pageable	分页实体
	 * @return
	 */
	@RequestMapping("/search/findInterfacesByUser")
	@RequiresPermissions(value={"businessServiceManagement:view", "businessServiceManagement:maintain"}, logical = Logical.OR)
	public Page<InterfaceVo> findInterfacesByUser(HttpInterfaceParam param, Pageable pageable) {
		if(StringUtils.isNoneBlank(param.getName())){
			param.setName("%" + param.getName() + "%");
		}
		
		if(StringUtils.isNoneBlank(param.getCode())){
			param.setCode("%" + param.getCode() + "%");
		}
		
		if(StringUtils.isEmpty(param.getCreateTime())){
			param.setCreateTime(Constants.CREATE_DATE);
		}
		
		if(StringUtils.isEmpty(param.getEndTime())){
			param.setEndTime(Constants.END_DATE);
		}
		User user = userSessionService.getCurrentAuthenticatedUser();
		
		
		DefinedBundle definedBundleProxy = definedBundleRepository
				.findByBundleName(Constants.COOKPROXY_NAME);
		
		DefinedBundle definedBundleFtp = definedBundleRepository
				.findByBundleName(Constants.COOKFTP_NAME);
		
		//获取总的记录数
		BigInteger total = (BigInteger) httpRepository.countInterfacesByUser(
							definedBundleProxy.getBundleCode(),
							definedBundleFtp.getBundleCode(),
							user.getId(), 
							param.getFieldId(), 
							param.getFieldSystemId(),
							param.getName(),
							param.getCode(),
							param.getStatus(), 
							param.getAuditStatus(), 
							param.getCreateTime(), 
							param.getEndTime()).get(0);
		if (total == null || total.longValue() <= 0) {
			return new PageImpl<InterfaceVo>(
					new ArrayList<InterfaceVo>(0), pageable, 0);
		}
		
		//获取所有接口信息
		List<Object[]> interfaceDatas = httpRepository.findInterfacesByUser(
							definedBundleProxy.getBundleCode(),
							definedBundleFtp.getBundleCode(),
							user.getId(), 
							param.getFieldId(), 
							param.getFieldSystemId(),
							param.getName(),
							param.getCode(),
							param.getStatus(), 
							param.getAuditStatus(), 
							param.getCreateTime(), 
							param.getEndTime(), 
							pageable.getPageNumber()
							* pageable.getPageSize(), 
							pageable.getPageSize());
		
		List<InterfaceVo> result = new ArrayList<InterfaceVo>(interfaceDatas.size());
		for (Object[] object : interfaceDatas) {
			InterfaceVo interfaceVo = new InterfaceVo();
			
			interfaceVo.setInterfaceId(object[0] != null ? (String) object[0] : "");
			interfaceVo.setFieldId(object[1] != null ? (String) object[1] : "");
			interfaceVo.setFieldSystemId(object[2] != null ? (String) object[2] : "");
			interfaceVo.setFieldName(object[3] != null ? (String) object[3] : "");
			interfaceVo.setSystemName(object[4] != null ? (String) object[4] : "");
			interfaceVo.setInterfaceName(object[5] != null ? (String) object[5] : "");
			interfaceVo.setInterfaceCode(object[6] != null ? (String) object[6] : "");
			if(object[7] != null){
				if(StringUtils.equals((String) object[7], IfType.WS.ValueCode)){
					interfaceVo.setInterfaceType("WEBSERVICE");
				}else if(StringUtils.equals((String) object[7], IfType.REST.ValueCode)){
					interfaceVo.setInterfaceType("REST");
				}else if(StringUtils.equals((String) object[7], IfType.FTP.ValueCode)){
					interfaceVo.setInterfaceType("FTP");
				}else{
					interfaceVo.setInterfaceType("");
				}
			}else{
				interfaceVo.setInterfaceType("");
			}
			interfaceVo.setType(object[7] != null ? (String) object[7] : "");
			if(object[8] != null){
				if(StringUtils.equals((String) object[8], AuditStatusType.UNAUDITED.ValueCode)){
					interfaceVo.setAuditStatus("未审核");
				}else if(StringUtils.equals((String) object[8], AuditStatusType.AUDITED.ValueCode)){
					interfaceVo.setAuditStatus("已审核");
				}else{
					interfaceVo.setAuditStatus("");
				}
			}else{
				interfaceVo.setAuditStatus("");
			}
			
			interfaceVo.setCreatedDate(object[9] != null ? fastDateFormat1.format(object[9]) : "");
			interfaceVo.setInterfaceVersion(object[10] != null ? (String) object[10] : "");
			interfaceVo.setInterfaceDes(object[11] != null ? (String) object[11] : "");
			interfaceVo.setInterfaceStatus(object[12] != null ? (String) object[12] : "");
			interfaceVo.setBundleName(object[13] != null ? (String) object[13] : "");
			interfaceVo.setBundleType(object[14] != null ? (String) object[14] : "");
			result.add(interfaceVo);
		}
		Page<InterfaceVo> page = new PageImpl<InterfaceVo>(result,
				pageable, total.longValue());
		
		return page;
	}
	
	/**
	 * 服务注册中获取所有的接口	
	 * @param wsdlAddress 前端传过来的webservice的wsdl地址
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/getInterfaceCode", produces="application/json")
	@RequiresPermissions(value={"serviceRegistration"})
	public String getInterfaceCode(String wsdlAddress) {
		JsonObject jsonObject = new JsonObject();
		String interfaceCodes = "";
		try {
			interfaceCodes = wsdlMetaDataService.getInterfaceCodes(wsdlAddress);
		}catch(WSDLException e){
			e.printStackTrace();
			jsonObject.addProperty("backValue", false);
			jsonObject.addProperty("errorDes", "接口原始地址无法访问，请确认网络是否能正常连接以及地址是否填写正确！");
			return jsonObject.toString();
		}catch (Exception e) {
			jsonObject.addProperty("backValue", false);
			jsonObject.addProperty("errorDes", "服务异常，获取接口编码失败，请稍后重试或联系管理员！");
			return jsonObject.toString();
		}
            
		jsonObject.addProperty("backValue", true);
		jsonObject.addProperty("interfaceCodes", interfaceCodes);
		
    	return jsonObject.toString();
	}
	
	
	/**
	 * webService和rest接口注册
	 * @param interfaceDatas 前端传过来的表单数据（格式：json字符串）
	 * @return
	 * @throws NoSuchObjectException 
	 */
	@RequestMapping(value="/httpServiceRegister", produces="application/json", method=RequestMethod.POST)
	@RequiresPermissions(value={"serviceRegistration"})
    public String httpServiceRegister(@RequestBody String interfaceDatas) {
		JsonObject jsonObject = new JsonObject();
		try {
			serviceManagerService.httpServiceRegister(interfaceDatas);
			jsonObject.addProperty("backValue", true);
		} catch (NoSuchObjectException e) {
			e.printStackTrace();
			jsonObject.addProperty("backValue", false);
			jsonObject.addProperty("errorDes", "注册失败！");
		} catch (ServiceHandlerException e) {
			e.printStackTrace();
			jsonObject.addProperty("backValue", false);
			jsonObject.addProperty("errorDes", e.getMessage());
		}
		
		return jsonObject.toString();
    } 
	
	
	/**
	 * webservice和rest接口更新
	 * @param interfaceDatas	前端传过来的表单数据（格式：json字符串）
	 * @return
	 * @throws NoSuchObjectException 
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value="/httpServiceUpdate", produces="application/json", method=RequestMethod.POST)
	@RequiresPermissions(value={"businessServiceManagement:maintain"})
    public String httpServiceUpdate(@RequestBody String interfaceDatas) throws NoSuchObjectException{
		JsonObject jsonObject = new JsonObject();
		try {
			serviceManagerService.httpServiceUpdate(interfaceDatas);
			jsonObject.addProperty("backValue", true);
		} catch (NoSuchObjectException e) {
			jsonObject.addProperty("backValue", false);
			jsonObject.addProperty("errorDes", "更新失败！");
		} catch (ServiceHandlerException e) {
			jsonObject.addProperty("backValue", false);
			jsonObject.addProperty("errorDes", e.getMessage());
		}
		
		return jsonObject.toString();
		
		
    } 
	
	/**
	 * webservice和rest接口版本升级
	 * @param interfaceDatas 前端传过来的表单数据（格式：json字符串）
	 * @return
	 * @throws NoSuchObjectException 
	 */
	@RequestMapping(value="/httpServiceUpVersion", produces="application/json", method=RequestMethod.POST)
	@RequiresPermissions(value={"businessServiceManagement:maintain"})
    public String httpServiceUpVersion(@RequestBody String interfaceDatas) throws NoSuchObjectException {
		JsonObject jsonObject = new JsonObject();
		try {
			serviceManagerService.httpServiceUpVersion(interfaceDatas);
			jsonObject.addProperty("backValue", true);
		} catch (NoSuchObjectException e) {
			jsonObject.addProperty("backValue", false);
			jsonObject.addProperty("errorDes", "版本升级失败！");
		} catch (ServiceHandlerException e) {
			jsonObject.addProperty("backValue", false);
			jsonObject.addProperty("errorDes", e.getMessage());
		}
		
		return jsonObject.toString();
    }
	

	/**
	 * 根据id对某个接口进行停用和启用操作
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/updateInterfaceStatus", produces="application/json")
	@RequiresPermissions(value={"businessServiceManagement:maintain"})
	public String updateInterfaceStatus(String id, String interfaceType){
		JsonObject jsonObject = new JsonObject();
		try {
			Ftp ftp = ftpRepository.findOne(Ftp.idSpecification(id));
			String ifStatus = "";
			if(ftp != null){
				ifStatus = ftp.getStatus();
			}
			serviceManagerService.updateInterfaceStatus(id);
			if (StringUtils.equals(interfaceType, IfType.FTP.ValueCode)) {
				// 测试servicemix服务器是否可以连通
				try {
					ConnetServerTest.telnetConnect(eSBServerFactory.getESBServer());
				} catch (ServerMixException e) {
					//手动回滚事务
					if (StringUtils.equals(ifStatus,
							IfStatusType.ENABLE.ValueCode)) {
						ftp.setStatus(IfStatusType.ENABLE.ValueCode);
						ftpRepository.save(Arrays.asList(ftp));
					}else{
						ftp.setStatus(IfStatusType.DISABLE.ValueCode);
						ftpRepository.save(Arrays.asList(ftp));
					}
					throw new ServiceHandlerException(e.getMessage(),
							CommonUtils.CODE_CONNECT_SERVICEMIX_FAIED);
				}
				
				if (StringUtils.equals(ifStatus,
						IfStatusType.ENABLE.ValueCode)) {
					try{
						boolean status = FtpRouteHandleUtil.process(Constants.STOP_CAMEL, ftp.getInterfacecode());
						if(!status){
							throw new ServiceHandlerException(CommonUtils.MSG_STOP_FTP_RETOUTER_FAIED, 
									CommonUtils.CODE_STOP_FTP_RETOUTER_FAIED);
						}
						
					}catch(Exception e){
						//手动回滚事务
						ftp.setStatus(IfStatusType.ENABLE.ValueCode);
						ftpRepository.save(Arrays.asList(ftp));
						throw new ServiceHandlerException(CommonUtils.MSG_STOP_FTP_RETOUTER_FAIED, 
								CommonUtils.CODE_STOP_FTP_RETOUTER_FAIED);
					}
				}else if (StringUtils.equals(ifStatus,
						IfStatusType.DISABLE.ValueCode)) {
					try{
						boolean status = FtpRouteHandleUtil.process(Constants.RESTART_CAMEL, ftp.getInterfacecode());
						if(!status){
							throw new ServiceHandlerException(CommonUtils.MSG_START_FTP_RETOUTER_FAIED, 
									CommonUtils.CODE_START_FTP_RETOUTER_FAIED);
						}
						
					}catch(Exception e){
						//手动回滚事务
						ftp.setStatus(IfStatusType.DISABLE.ValueCode);
						ftpRepository.save(Arrays.asList(ftp));
						throw new ServiceHandlerException(CommonUtils.MSG_START_FTP_RETOUTER_FAIED, 
								CommonUtils.CODE_START_FTP_RETOUTER_FAIED);
					}
				}
			}
			jsonObject.addProperty("backValue", true);
		}catch (ServiceHandlerException e) {
			jsonObject.addProperty("backValue", false);
			jsonObject.addProperty("errorDes", e.getMessage());
		}
		
		return jsonObject.toString();
	}
	
	
	/**
	 * 根据接口id和接口类型对接口进行审核处理
	 * @param id
	 * @param interfaceType
	 * @return
	 */
	@RequestMapping(value="/updateInterfaceAuditStatus", produces="application/json")
	@RequiresPermissions(value={"serviceAudit"})
	public String updateInterfaceAuditStatus(String id, String interfaceType){
		JsonObject jsonObject = new JsonObject();
		try {
			serviceManagerService.updateInterfaceAuditStatus(id, interfaceType);
			if (StringUtils.equals(interfaceType, IfType.FTP.ValueCode)) {
					Ftp ftp = ftpRepository.findOne(Ftp.idSpecification(id));
					// 测试servicemix服务器是否可以连通
					try {
						ConnetServerTest.telnetConnect(eSBServerFactory.getESBServer());
					} catch (ServerMixException e) {
						//手动回滚事务
						ftp.setAuditStatus(AuditStatusType.UNAUDITED.ValueCode);
						ftp.setStatus(IfStatusType.DISABLE.ValueCode);
						ftpRepository.save(Arrays.asList(ftp));
						throw new ServiceHandlerException(e.getMessage(),
								CommonUtils.CODE_CONNECT_SERVICEMIX_FAIED);
					}
					try{
						boolean status = FtpRouteHandleUtil.process(Constants.RESTART_CAMEL, ftp.getInterfacecode());
						if(!status){
							throw new ServiceHandlerException(CommonUtils.MSG_CREATE_FTP_RETOUTER_FAIED, 
									CommonUtils.CODE_CREATE_FTP_RETOUTER_FAIED);
						}
					}catch(Exception e){
						//手动回滚事务
						ftp.setAuditStatus(AuditStatusType.UNAUDITED.ValueCode);
						ftp.setStatus(IfStatusType.DISABLE.ValueCode);
						ftpRepository.save(Arrays.asList(ftp));
						throw new ServiceHandlerException(CommonUtils.MSG_CREATE_FTP_RETOUTER_FAIED, 
								CommonUtils.CODE_CREATE_FTP_RETOUTER_FAIED);
					}
					// 记录用户操作日志
					userLogService.save(UserLogOpt.MaintenanceServiceVerify, null,
							String.format("审核了“%s”接口", ftp.getInterfaceName()));
			}
			User user = null;
			Ftp ftp = ftpRepository.findOne(Ftp.idSpecification(id));
			Http http = httpRepository.findOne(Http.idSpecification(id));
			String sucessIfNames = "";
			if(ftp == null){
				user = userRepository.findByUserCode(http.getCreator());
				sucessIfNames = http.getName();
			}else{
				user = userRepository.findByUserCode(ftp.getCreator());
				sucessIfNames = ftp.getInterfaceName();
			}
			
			//发送邮件
			Map<String, String> emailMap = new HashMap<String, String>();
			emailMap.put("userCode", user.getUserCode());
			emailMap.put("emailAddress", user.getEmailAddress());
			emailMap.put("sucessIfNames", sucessIfNames);
			String requestIpAndPort = FtpRouteHandleUtil.getLocalHost();
			SimpleDateFormat DateTimeFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
			String time = DateTimeFormat.format(new Date()).replace(" ", "#");
			String requestUrl = "http://"+requestIpAndPort+"/pages/UserManagement/UserLogin.html?time=" + time;
			emailMap.put("requestUrl", requestUrl);
			try {
				sendEmailService.CookSendEmail(emailMap, Constants.SERVICE_AUDIT_SUBJECT,
						Constants.SERVICE_AUDIT_TEMPLATE2);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			
			jsonObject.addProperty("backValue", true);
		}catch (ServiceHandlerException e) {
			
			jsonObject.addProperty("backValue", false);
			jsonObject.addProperty("errorDes", e.getMessage());
		}
		
		return jsonObject.toString();
	}
	
	
	/**
	 * 批量对接口进行审核处理
	 * @param id
	 * @param interfaceType
	 * @return
	 */
	@RequestMapping(value="/batchAuditIfStatus", produces="application/json")
	@RequiresPermissions(value={"serviceAudit"})
	public String batchAuditIfStatus(String httpIds, String ftpIds){
		//返回到页面的结果集map
		Map<String, String> handleResutlMap = new HashMap<String, String>();
		//用于发送邮件的结果集map,map中第一个参数为接口名称，第二个参数为接口状态，value为接口创建人邮箱地址
		MultiKeyMap<String, User> sendEmailMap = new MultiKeyMap<String, User>();
		
		Map<User, Map<String, String>> map = new HashMap<>();
		//审核http接口
		if(StringUtils.isNotBlank(httpIds)){
			serviceManagerService.batchAuditHttpIfs(handleResutlMap, sendEmailMap, httpIds);
		}
		
		//审核ftp接口
		if(StringUtils.isNotBlank(ftpIds)){
			serviceManagerService.batchAuditFtpIfs(handleResutlMap, sendEmailMap, ftpIds);
		}
		
		//处理邮件map
		for (MultiKey<? extends String> key : sendEmailMap.keySet()) {
			User mapKey = sendEmailMap.get(key);
			if(map.containsKey(mapKey)){
				//包含这个用户
				map.get(mapKey).put(key.getKey(0), key.getKey(1));
			}else{
				//不包含
				Map<String, String> ifMap = new HashMap<String, String>();
				ifMap.put(key.getKey(0), key.getKey(1));
				map.put(mapKey, ifMap);
			}
		}
		
		//根据不同的用户发送邮件
		for (User user : map.keySet()) {
			String sucessIfNames = "";
			String faildIfNames = "";
			Map<String, String> ifMap = map.get(user);
			for(String ifKey : ifMap.keySet()){
				if(StringUtils.equals(ifMap.get(ifKey), "1")){
					sucessIfNames += (StringUtils.isNotBlank(sucessIfNames) == true?",":"") + ifKey;
				}else{
					faildIfNames += (StringUtils.isNotBlank(faildIfNames) == true?",":"") + ifKey;
				}
			}
			
			//发送邮件
			Map<String, String> emailMap = new HashMap<String, String>();
			emailMap.put("userCode", user.getUserCode());
			emailMap.put("emailAddress", user.getEmailAddress());
			emailMap.put("sucessIfNames", sucessIfNames);
			emailMap.put("faildIfNames", faildIfNames);
			String requestIpAndPort = FtpRouteHandleUtil.getLocalHost();
			SimpleDateFormat DateTimeFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
			String time = DateTimeFormat.format(new Date()).replace(" ", "#");
			String requestUrl = "http://"+requestIpAndPort+"/pages/UserManagement/UserLogin.html?time=" + time;
			emailMap.put("requestUrl", requestUrl);
			try {
				sendEmailService.CookSendEmail(emailMap, Constants.SERVICE_AUDIT_SUBJECT,
						Constants.SERVICE_AUDIT_TEMPLATE);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		JsonObject jsonObject = new JsonObject(); 
		JsonArray audits = new JsonArray();
		for(String ifName : handleResutlMap.keySet()){
			JsonObject audit = new JsonObject(); 
			audit.addProperty("ifName", ifName);
			audit.addProperty("ifAuditDes", handleResutlMap.get(ifName));
			audits.add(audit);
		}
		jsonObject.add("auditResult", audits);
		return jsonObject.toString();
	}
	
	
	
	
	/**
	 * 根据id对指定的接口卸载
	 * @param id
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value="/interfaceUninstall", produces="application/json")
	@RequiresPermissions(value={"businessServiceManagement:maintain"})
	public String interfaceUninstall(String id) {
		JsonObject jsonObject = new JsonObject();
		try {
			serviceManagerService.interfaceUninstall(id);
			jsonObject.addProperty("backValue", true);
		}catch (ServiceHandlerException e) {
			jsonObject.addProperty("backValue", false);
			jsonObject.addProperty("errorDes", e.getMessage());
		}
		
		return jsonObject.toString();
	}
	
	@RequestMapping(value="/findIfMaxVersionById", produces="application/json")
	public String findIfMaxVersionByCode(String interfaceCode) {
		List<String> versions = httpRepository.findIfMaxVersionByCode(interfaceCode);
		String maxVersion = versions.get(0);
		JsonObject result = new JsonObject();
		result.addProperty("maxVersion", maxVersion);
		return result.toString();
	}
	
	/**
	 * 根据id获取webservice和rest接口数据进行回显
	 * @param id
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value="/findIfById", produces="application/json")
	@RequiresPermissions(value={"businessServiceManagement:view", "businessServiceManagement:maintain"}, logical = Logical.OR)
	public String findIfById(String id) {
		Http http = httpRepository.findOne(Http.idSpecification(id));
		Gson gs = new Gson(); 
		
		FieldSystem  fieldSystem = http.getFieldSystem();
		String fieldId = fieldSystem.getField().getId();
		String fieldSystemId = fieldSystem.getId();
		http.setFieldSystem(null);
		
		JsonArray json = new JsonArray();
		if (!CollectionUtils.isEmpty(http.getVisibleFieldSystems())) {
			for (FieldSystem visibleFieldSystem : http.getVisibleFieldSystems()) {
				JsonObject result = new JsonObject();
				result.addProperty("fieldSystemId", visibleFieldSystem.getId());
				result.addProperty("fieldName", visibleFieldSystem.getField().getName());
				result.addProperty("fieldSystemName", visibleFieldSystem.getName());
				json.add(result);
			}
		}
		http.setVisibleFieldSystems(null);
		
		
		JsonArray DefinedBundlejson = new JsonArray();
		if (!CollectionUtils.isEmpty(http.getDefinedbundles())) {
			for (DefinedBundle definedBundle : http.getDefinedbundles()) {
				JsonObject result = new JsonObject();
				result.addProperty("bundleId", definedBundle.getId());
				result.addProperty("bundleCode", definedBundle.getBundleCode());
				result.addProperty("isDefinedBundle", definedBundle.getIsDefinedBundle());
				result.addProperty("bundleJarName", definedBundle.getBundleJarName());
				result.addProperty("bundleName", definedBundle.getBundleName());
				DefinedBundlejson.add(result);
			}
		}
		http.setDefinedbundles(null);
		
		JsonArray interReqQJsonDatas = new JsonArray();
		Set<IfReqQuantity> interReqQSet = http.getInterfaceRequestQuantity();
		for (IfReqQuantity interfaceRequestQuantity : interReqQSet) {
			interfaceRequestQuantity.setHttp(null);
			JsonObject jsonObject = new JsonObject();
			jsonObject.addProperty("requestQuantityId", interfaceRequestQuantity.getId());
			jsonObject.addProperty("requestThreshold", interfaceRequestQuantity.getRequestThreshold());
			jsonObject.addProperty("requestMax", interfaceRequestQuantity.getRequestMax());
			jsonObject.addProperty("requestUnit", interfaceRequestQuantity.getRequestUnit());
			interReqQJsonDatas.add(jsonObject);
		}
		http.setInterfaceRequestQuantity(null);
		
		http.getInterfaceToken();
		http.setInterfaceToken(null);
		
		JsonArray InterfaceParameterJsonDatas = new JsonArray();
		Set<IfParameter> interfaceParameterSet = http.getInterfaceParameter();
		for (IfParameter interfaceParameter : interfaceParameterSet) {
			interfaceParameter.setHttp(null);
			JsonObject jsonObject = new JsonObject();
			jsonObject.addProperty("paramId", interfaceParameter.getId());
			jsonObject.addProperty("paramType", interfaceParameter.getType());
			jsonObject.addProperty("paramName", interfaceParameter.getName());
			jsonObject.addProperty("paramDataType", interfaceParameter.getDataType());
			jsonObject.addProperty("paramDefaultValue", interfaceParameter.getDefaultValue());
			jsonObject.addProperty("isNeed", interfaceParameter.getIsNeed());
			jsonObject.addProperty("paramDes", interfaceParameter.getDesc());
			
			InterfaceParameterJsonDatas.add(jsonObject);
		}
		http.setInterfaceParameter(null);
		
		JsonObject jsonObject = new JsonObject();
		jsonObject = GsonUtil.getDefaultJsonParser().parse(gs.toJson(http)).getAsJsonObject();
		jsonObject.addProperty("filedId", fieldId);
		jsonObject.addProperty("filedSystemId", fieldSystemId);
    	jsonObject.add("interfaceRequestQuantity", interReqQJsonDatas);
    	jsonObject.add("interfaceParameter", InterfaceParameterJsonDatas);
    	jsonObject.add("visibleFieldSystems", json);
    	jsonObject.add("DefinedBundles", DefinedBundlejson);
    	return jsonObject.toString();
    	
	}
	
	/**
	 * ftp接口注册
	 * @param interfaceDatas
	 * @return
	 * @throws ParseException 
	 * @throws IOException
	 */
	@RequestMapping(value = "/ftpServiceRegister", produces = "application/json", method=RequestMethod.POST)
	@RequiresPermissions(value={"serviceRegistration"})
	public String ftpServiceRegister(@RequestBody String interfaceDatas) throws ParseException {
		JsonObject jsonObject = new JsonObject();
		try {
			serviceManagerService.ftpServiceRegister(interfaceDatas);
			jsonObject.addProperty("backValue", true);
		}catch (ServiceHandlerException e) {
			jsonObject.addProperty("backValue", false);
			jsonObject.addProperty("errorDes", e.getMessage());
		}
		
		return jsonObject.toString();
		
	}
	
	/**
	 * ftp接口信息更新
	 * @param interfaceDatas
	 * @return
	 * @throws ParseException 
	 * @throws IOException
	 */
	@RequestMapping(value = "/ftpServiceUpdate", produces = "application/json", method=RequestMethod.POST)
	@RequiresPermissions(value={"businessServiceManagement:maintain"})
	public String ftpServiceUpdate(@RequestBody String interfaceDatas) throws ParseException {
		JsonObject jsonObject = new JsonObject();
		try {
			serviceManagerService.ftpServiceUpdate(interfaceDatas);
			jsonObject.addProperty("backValue", true);
		}catch (ServiceHandlerException e) {
			jsonObject.addProperty("backValue", false);
			jsonObject.addProperty("errorDes", e.getMessage());
		}
		
		return jsonObject.toString();
		
	}	
			
			
			
	/**
	 * 根据id获取ftp接口数据进行回显
	 * @param id
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/findIfByIdFtp", produces = "application/json")
	@RequiresPermissions(value={"businessServiceManagement:view", "businessServiceManagement:maintain"}, logical = Logical.OR)
	public String findIfByIdFtp(String id) {
		Ftp ftp = ftpRepository.findOne(Ftp.idSpecification(id));
		Gson gs = new Gson();

		FieldSystem fieldSystem = ftp.getFieldSystem();
		String fieldId = fieldSystem.getField().getId();
		String fieldSystemId = fieldSystem.getId();
		String systemCode = fieldSystem.getCode();
		ftp.setFieldSystem(null);

		JsonArray json = new JsonArray();
		if (!CollectionUtils.isEmpty(ftp.getVisibleFieldSystems())) {
			for (FieldSystem visibleFieldSystem : ftp.getVisibleFieldSystems()) {
				JsonObject result = new JsonObject();
				result.addProperty("fieldSystemId", visibleFieldSystem.getId());
				result.addProperty("fieldName", visibleFieldSystem.getField().getName());
				result.addProperty("fieldSystemName", visibleFieldSystem.getName());
				json.add(result);
			}
		}
		ftp.setVisibleFieldSystems(null);

		JsonArray DefinedBundlejson = new JsonArray();
		if (!CollectionUtils.isEmpty(ftp.getDefinedbundles())) {
			for (DefinedBundle definedBundle : ftp.getDefinedbundles()) {
				JsonObject result = new JsonObject();
				result.addProperty("bundleId", definedBundle.getId());
				result.addProperty("bundleCode", definedBundle.getBundleCode());
				result.addProperty("isDefinedBundle", definedBundle.getIsDefinedBundle());
				result.addProperty("bundleJarName", definedBundle.getBundleJarName());
				result.addProperty("bundleName", definedBundle.getBundleName());
				DefinedBundlejson.add(result);
			}
		}
		ftp.setDefinedbundles(null);

		JsonArray ftpServerSourceDatas = new JsonArray();
		JsonArray ftpServerDesDatas = new JsonArray();
		Set<FtpServer> ftpServerSet = ftp.getFtpServers();
		for (FtpServer ftpServer : ftpServerSet) {
			ftpServer.setFtp(null);

			if (StringUtils.equals(ftpServer.getHostType(), FtpHostType.SOURCE_HOST.ValueCode)) {
				JsonObject jsonSourceObject = new JsonObject();
				jsonSourceObject.addProperty("ftpServerId", ftpServer.getId());
				jsonSourceObject.addProperty("host", ftpServer.getHost());
				jsonSourceObject.addProperty("port", ftpServer.getPort());
				jsonSourceObject.addProperty("userName", ftpServer.getUserName());
				jsonSourceObject.addProperty("password", ftpServer.getPassword());
				jsonSourceObject.addProperty("fileDir", ftpServer.getFileDir());
				jsonSourceObject.addProperty("ifCover", ftpServer.getIfCover());
				jsonSourceObject.addProperty("ifDelSource", ftpServer.getIfDelSource());
				jsonSourceObject.addProperty("passiveMode", ftpServer.getPassiveMode());
				jsonSourceObject.addProperty("ifAnonymous", ftpServer.getIfAnonymous());
				jsonSourceObject.addProperty("hostType", ftpServer.getHostType());
				if(StringUtils.isNoneBlank(ftpServer.getFileName())){
					JsonObject jsonStr = GsonUtil.getDefaultJsonParser().parse(ftpServer.getFileName()).getAsJsonObject();
					if(StringUtils.equals(jsonStr.get("filterType").getAsString(), "1")){
						jsonSourceObject.addProperty("matchMode", "正则匹配");
					}else if(StringUtils.equals(jsonStr.get("filterType").getAsString(), "2")){
						jsonSourceObject.addProperty("matchMode", "名称匹配");
					}
					jsonSourceObject.addProperty("fileName", jsonStr.get("checkStr").getAsString());
				}else{
					jsonSourceObject.addProperty("matchMode", "无匹配");
					jsonSourceObject.addProperty("fileName", "");
				}
				jsonSourceObject.addProperty("serverCode", ftpServer.getServerCode());
				jsonSourceObject.addProperty("fieldId", ftpServer.getOwnFieldSystem().getFieldId());
				jsonSourceObject.addProperty("fieldSystemId", ftpServer.getOwnFieldSystem().getId());
				ftpServerSourceDatas.add(jsonSourceObject);
			} else if (StringUtils.equals(ftpServer.getHostType(), FtpHostType.TARGET_HOST.ValueCode)) {
				JsonObject jsonDesObject = new JsonObject();
				jsonDesObject.addProperty("ftpServerId", ftpServer.getId());
				jsonDesObject.addProperty("host", ftpServer.getHost());
				jsonDesObject.addProperty("port", ftpServer.getPort());
				jsonDesObject.addProperty("userName", ftpServer.getUserName());
				jsonDesObject.addProperty("password", ftpServer.getPassword());
				jsonDesObject.addProperty("fileDir", ftpServer.getFileDir());
				jsonDesObject.addProperty("ifCover", ftpServer.getIfCover());
				jsonDesObject.addProperty("ifDelSource", ftpServer.getIfDelSource());
				jsonDesObject.addProperty("passiveMode", ftpServer.getPassiveMode());
				jsonDesObject.addProperty("ifAnonymous", ftpServer.getIfAnonymous());
				jsonDesObject.addProperty("hostType", ftpServer.getHostType());
				jsonDesObject.addProperty("serverCode", ftpServer.getServerCode());
				jsonDesObject.addProperty("fieldId", ftpServer.getOwnFieldSystem().getFieldId());
				jsonDesObject.addProperty("fieldSystemId", ftpServer.getOwnFieldSystem().getId());
				ftpServerDesDatas.add(jsonDesObject);
			} else {

			}

		}
		ftp.setFtpServers(null);
		
		
		JsonArray ifScheduleDatas = new JsonArray();
		Set<IfSchedule> ifScheduleSet = ftp.getIfSchedules();
		for (IfSchedule ifSchedule : ifScheduleSet) {
			ifSchedule.setFtp(null);
			JsonObject jsonObject = new JsonObject();
			jsonObject.addProperty("ifscheduleId", ifSchedule.getId());
			jsonObject.addProperty("beginTime", fastDateFormat1.format(ifSchedule.getBeginTime()));
			jsonObject.addProperty("endTime", fastDateFormat1.format(ifSchedule.getEndTime()));
			jsonObject.addProperty("runCyc", ifSchedule.getRunCyc());
			jsonObject.addProperty("runWay", ifSchedule.getRunWay());
			jsonObject.addProperty("dayOfWeek", ifSchedule.getDayOfWeek());
			/*jsonObject.addProperty("fileCachePath", ifSchedule.getFileCachePath());*/
			ifScheduleDatas.add(jsonObject);
		}
		ftp.setIfSchedules(null);
		
		
		String routePublishUrl = "http://" + FtpRouteHandleUtil.getLocalHost() + "/ftp/" + systemCode + "/" + ftp.getVersion() + "/" + ftp.getInterfacecode();

		JsonObject jsonObject = new JsonObject();
		jsonObject = GsonUtil.getDefaultJsonParser().parse(gs.toJson(ftp)).getAsJsonObject();
		jsonObject.addProperty("filedId", fieldId);
		jsonObject.addProperty("filedSystemId", fieldSystemId);
		jsonObject.addProperty("routePublishUrl", routePublishUrl);
		jsonObject.add("ftpServerSourceDatas", ftpServerSourceDatas);
		jsonObject.add("ftpServerDesDatas", ftpServerDesDatas);
		jsonObject.add("visibleFieldSystems", json);
		jsonObject.add("DefinedBundles", DefinedBundlejson);
		jsonObject.add("ifSchedules", ifScheduleDatas);
		return jsonObject.toString();

	}
	
	/**
	 * 根据id获取接口信息数据在服务浏览页面回显
	 * 
	 * @param id
	 * @return
	 * @throws NoSuchObjectException 
	 * @throws IOException
	 */
	@RequestMapping(value = "/findIfByIdForServiceScan", produces = "application/json")
	@RequiresPermissions(value={"businessServiceManagement:view", "businessServiceManagement:maintain"}, logical = Logical.OR)
	public String findIfByIdForServiceScan(String id) throws NoSuchObjectException{
		JsonObject jsonObject = new JsonObject();
		Gson gs = new Gson();
		Http http = httpRepository.findOne(Http.idSpecification(id));
		if (http != null) {
			http.setFieldSystem(null);
			http.setInterfaceRequestQuantity(null);

			JsonArray IfParameterReqJsonDatas = new JsonArray();
			JsonArray IfParameterRepJsonDatas = new JsonArray();
			Set<IfParameter> interfaceParameterSet = http.getInterfaceParameter();
			for (IfParameter interfaceParameter : interfaceParameterSet) {
				interfaceParameter.setHttp(null);
				String paramType = interfaceParameter.getType();
				if(StringUtils.equals(paramType, ParameterType.REQUEST.ValueCode)){
					JsonObject jsonObjectParam = new JsonObject();
					/*jsonObjectParam.addProperty("paramId", interfaceParameter.getId());*/
					jsonObjectParam.addProperty("paramName", interfaceParameter.getName());
					/*jsonObjectParam.addProperty("paramType", interfaceParameter.getType());*/
					jsonObjectParam.addProperty("paramDataType", IfParameterType.get(interfaceParameter.getDataType()).ValueName);
					if(StringUtils.equals(interfaceParameter.getIsNeed(), "0")){
						jsonObjectParam.addProperty("isNeed", "否");
					}else{
						jsonObjectParam.addProperty("isNeed", "是");
					}
					jsonObjectParam.addProperty("paramDefaultValue", interfaceParameter.getDefaultValue());
					jsonObjectParam.addProperty("paramDes", interfaceParameter.getDesc());
	
					IfParameterReqJsonDatas.add(jsonObjectParam);
				}else{
					JsonObject jsonObjectParam = new JsonObject();
					/*jsonObjectParam.addProperty("paramId", interfaceParameter.getId());
					jsonObjectParam.addProperty("paramType", interfaceParameter.getType());*/
					jsonObjectParam.addProperty("paramName", interfaceParameter.getName());
					jsonObjectParam.addProperty("paramDataType", IfParameterType.get(interfaceParameter.getDataType()).ValueName);
					/*if(StringUtils.equals(interfaceParameter.getIsNeed(), "0")){
						jsonObjectParam.addProperty("isNeed", "否");
					}else{
						jsonObjectParam.addProperty("isNeed", "是");
					}*/
					jsonObjectParam.addProperty("paramDes", interfaceParameter.getDesc());
	
					IfParameterRepJsonDatas.add(jsonObjectParam);
				}
			}
			http.setInterfaceParameter(null);

			http.setInterfaceToken(null);

			http.setDefinedbundles(null);

			http.setVisibleFieldSystems(null);

			
			jsonObject = GsonUtil.getDefaultJsonParser().parse(gs.toJson(http)).getAsJsonObject();
			jsonObject.add("IfParameterReqJsonDatas", IfParameterReqJsonDatas);
			jsonObject.add("IfParameterRepJsonDatas", IfParameterRepJsonDatas);
			jsonObject.addProperty("backValue", true);

			return jsonObject.toString();
		} else {
			Ftp ftp = ftpRepository.findOne(Ftp.idSpecification(id));
				if(ftp != null){
					
				ftp.setFieldSystem(null);
				ftp.setDefinedbundles(null);
				ftp.setVisibleFieldSystems(null);
				
				
				JsonArray FtpJsonSourceDatas = new JsonArray();
				JsonArray FtpJsonDesDatas = new JsonArray();
				Set<FtpServer> FtpSet = ftp.getFtpServers();
				for (FtpServer ftpServer : FtpSet) {
					ftpServer.setFtp(null);
					if(StringUtils.equals(ftpServer.getHostType(), FtpHostType.SOURCE_HOST.ValueCode)){
						ftpServer.setFtp(null);
						ftpServer.setOwnFieldSystem(null);
						JsonObject jsonObjectParam = new JsonObject();
						jsonObjectParam.addProperty("host", ftpServer.getHost());
						jsonObjectParam.addProperty("port", ftpServer.getPort());
						if(StringUtils.equals(ftpServer.getIfAnonymous(), FtpAccessType.ANONYMOUS.ValueCode)){
							jsonObjectParam.addProperty("isAnonmous", "是");
						}else if(StringUtils.equals(ftpServer.getIfAnonymous(), FtpAccessType.UNANONYMOUS.ValueCode)){
							jsonObjectParam.addProperty("isAnonmous", "否");
						}
						
						if(StringUtils.equals(ftpServer.getIfDelSource(), FtpSourceFileHanderType.DELETE.ValueCode)){
							jsonObjectParam.addProperty("isDelSourceFile", "是");
						}else if(StringUtils.equals(ftpServer.getIfDelSource(), FtpAccessType.UNANONYMOUS.ValueCode)){
							jsonObjectParam.addProperty("isDelSourceFile", "否");
						}
						
						
						jsonObjectParam.addProperty("userName", ftpServer.getUserName());
						jsonObjectParam.addProperty("password", "******");
		
						FtpJsonSourceDatas.add(jsonObjectParam);
					}else if(StringUtils.equals(ftpServer.getHostType(), FtpHostType.TARGET_HOST.ValueCode)){
						ftpServer.setFtp(null);
						ftpServer.setOwnFieldSystem(null);
						JsonObject jsonObjectParam = new JsonObject();
						jsonObjectParam.addProperty("host", ftpServer.getHost());
						jsonObjectParam.addProperty("port", ftpServer.getPort());
						if(StringUtils.equals(ftpServer.getIfAnonymous(), FtpAccessType.ANONYMOUS.ValueCode)){
							jsonObjectParam.addProperty("isAnonmous", "是");
						}else if(StringUtils.equals(ftpServer.getIfAnonymous(), FtpAccessType.UNANONYMOUS.ValueCode)){
							jsonObjectParam.addProperty("isAnonmous", "否");
						}
						
						if(StringUtils.equals(ftpServer.getIfCover(), FtpTargetFileHanderType.COVER.ValueCode)){
							jsonObjectParam.addProperty("isCoverFile", "是");
						}else if(StringUtils.equals(ftpServer.getIfCover(), FtpTargetFileHanderType.UNCOVER.ValueCode)){
							jsonObjectParam.addProperty("isCoverFile", "否");
						}
						
						
						jsonObjectParam.addProperty("userName", ftpServer.getUserName());
						jsonObjectParam.addProperty("password", "******");
		
		
						FtpJsonDesDatas.add(jsonObjectParam);
					}
					
				}
				ftp.setFtpServers(null);
				JsonArray ifScheduleDatas = new JsonArray();
				if(StringUtils.equals(ftp.getIsSchedule(), ScheduleType.UNSCHEDULE.ValueCode)){
					JsonObject jsonObjectSchedule = new JsonObject();
					String routePublishUrl = "http://" + FtpRouteHandleUtil.getLocalHost() + "/ftp/" + ftp.getSystemCode() + "/" + ftp.getVersion() + "/" + ftp.getInterfacecode();
					jsonObjectSchedule.addProperty("scheduleDescription", String.format("%s", routePublishUrl));
					//jsonObjectSchedule.addProperty("fileCachePath", ifSchedule.getFileCachePath());
					ifScheduleDatas.add(jsonObjectSchedule);
				}else{
					Set<IfSchedule> ifScheduleSet = ftp.getIfSchedules();
					for (IfSchedule ifSchedule : ifScheduleSet) {
						ifSchedule.setFtp(null);
						JsonObject jsonObjectSchedule = new JsonObject();
						jsonObjectSchedule.addProperty("ifscheduleId", ifSchedule.getId());
						jsonObjectSchedule.addProperty("beginTime", fastDateFormat1.format(ifSchedule.getBeginTime()));
						jsonObjectSchedule.addProperty("endTime", fastDateFormat1.format(ifSchedule.getEndTime()));
						jsonObjectSchedule.addProperty("runCyc", ifSchedule.getRunCyc());
						jsonObjectSchedule.addProperty("runWay", ifSchedule.getRunWay());
						jsonObjectSchedule.addProperty("dayOfWeek", ifSchedule.getDayOfWeek());
						String dayOfWeek = ifSchedule.getDayOfWeek();
						if(StringUtils.equals(ifSchedule.getRunWay(), KettleJobScheduleCycleUnit.Once.ValueCode)){
							jsonObjectSchedule.addProperty("scheduleDescription", String.format("运行一次"));
						}
						if(StringUtils.equals(ifSchedule.getRunWay(), KettleJobScheduleCycleUnit.Day.ValueCode) && ifSchedule.getRunCyc() > 1){
							jsonObjectSchedule.addProperty("scheduleDescription", String.format("每  %s %s 运行一次",String.valueOf(ifSchedule.getRunCyc()), KettleJobScheduleCycleUnit.get(ifSchedule.getRunWay()).ValueName));
						}
						
						if(StringUtils.equals(ifSchedule.getRunWay(), KettleJobScheduleCycleUnit.Day.ValueCode) && ifSchedule.getRunCyc() == 1){
							if(StringUtils.isNotBlank(dayOfWeek)){
								String weeks = "";
								if(dayOfWeek.contains(",")){
									String[] dayOfWeeks = ifSchedule.getDayOfWeek().split(",");
									for (String week : dayOfWeeks) {
										weeks += (StringUtils.isNotBlank(weeks) == true?"、":"") + FtpScheduleUnit.get(week).ValueName;
									}
									jsonObjectSchedule.addProperty("scheduleDescription", String.format("每  %s %s 运行一次, 周执行日分别为  %s",String.valueOf(ifSchedule.getRunCyc()), KettleJobScheduleCycleUnit.get(ifSchedule.getRunWay()).ValueName, weeks));
								}else{
									jsonObjectSchedule.addProperty("scheduleDescription", String.format("每  %s %s 运行一次, 周执行日分别为  %s",String.valueOf(ifSchedule.getRunCyc()), KettleJobScheduleCycleUnit.get(ifSchedule.getRunWay()).ValueName, FtpScheduleUnit.get(dayOfWeek).ValueName));
								}
							}
							
						}
						
						if(!StringUtils.equals(ifSchedule.getRunWay(), KettleJobScheduleCycleUnit.Day.ValueCode) && 
								!StringUtils.equals(ifSchedule.getRunWay(), KettleJobScheduleCycleUnit.Once.ValueCode)){
							jsonObjectSchedule.addProperty("scheduleDescription", String.format("每  %s %s 运行一次",String.valueOf(ifSchedule.getRunCyc()), KettleJobScheduleCycleUnit.get(ifSchedule.getRunWay()).ValueName));
						}
						
						/*jsonObjectSchedule.addProperty("fileCachePath", ifSchedule.getFileCachePath());*/
						ifScheduleDatas.add(jsonObjectSchedule);
					}
				}
				
				ftp.setIfSchedules(null);
				
				jsonObject = GsonUtil.getDefaultJsonParser().parse(gs.toJson(ftp)).getAsJsonObject();
				jsonObject.add("ifScheduleDatas", ifScheduleDatas);
				jsonObject.add("FtpJsonSourceDatas", FtpJsonSourceDatas);
				jsonObject.add("FtpJsonDesDatas", FtpJsonDesDatas);
				jsonObject.addProperty("backValue", true);
				
				return jsonObject.toString();
			}else{
				jsonObject.addProperty("backValue", false);
				return jsonObject.toString();
			}
		}
	}
		
	
	
	/**
	 * 根据id获取接口信息数据在报文管理页面回显
	 * 
	 * @param id
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/findIfByIdForMsg", produces = "application/json")
	@RequiresPermissions(value={"businessServiceManagement:view", "businessServiceManagement:maintain"}, logical = Logical.OR)
	public String findIfByIdForMsg(String id) {
		JsonObject jsonObject = new JsonObject();
		Gson gs = new Gson();
		Http http = httpRepository.findOne(Http.idSpecification(id));
		if (http != null) {
			http.setFieldSystem(null);
			http.setInterfaceRequestQuantity(null);

			JsonArray InterfaceParameterJsonDatas = new JsonArray();
			Set<IfParameter> interfaceParameterSet = http.getInterfaceParameter();
			for (IfParameter interfaceParameter : interfaceParameterSet) {
				interfaceParameter.setHttp(null);
				JsonObject jsonObjectParam = new JsonObject();
				jsonObjectParam.addProperty("paramId", interfaceParameter.getId());
				jsonObjectParam.addProperty("paramType", interfaceParameter.getType());
				jsonObjectParam.addProperty("paramName", interfaceParameter.getName());
				jsonObjectParam.addProperty("paramDataType", interfaceParameter.getDataType());
				jsonObjectParam.addProperty("isNeed", interfaceParameter.getIsNeed());
				jsonObjectParam.addProperty("paramDefaultValue", interfaceParameter.getDefaultValue());
				jsonObjectParam.addProperty("paramDes", interfaceParameter.getDesc());
				
				InterfaceParameterJsonDatas.add(jsonObjectParam);
			}
			http.setInterfaceParameter(null);
			
			
			http.setInterfaceToken(null);

			http.setDefinedbundles(null);

			http.setVisibleFieldSystems(null);

			jsonObject = GsonUtil.getDefaultJsonParser().parse(gs.toJson(http)).getAsJsonObject();
			jsonObject.add("interfaceParameter", InterfaceParameterJsonDatas);
			jsonObject.addProperty("backValue", true);
			return jsonObject.toString();
		}else{
			jsonObject.addProperty("backValue", false);
			return jsonObject.toString();
		}
	}
	
	
	/**
	 * 根据id获取接口信息数据在报文管理页面回显
	 * 
	 * @param id
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/updateIfMessage", produces = "application/json", method=RequestMethod.POST)
	@RequiresPermissions(value={"businessServiceManagement:maintain"})
	public String updateIfMessage(@RequestBody String interfaceDatas) {
		JsonObject jsonObject = new JsonObject();
		try {
			serviceManagerService.updateIfMessage(interfaceDatas);
			jsonObject.addProperty("backValue", true);
		} catch (NoSuchObjectException e) {
			jsonObject.addProperty("backValue", false);
			jsonObject.addProperty("errorDes", "报文修改失败！");
		} catch (ServiceHandlerException e) {
			jsonObject.addProperty("backValue", false);
			jsonObject.addProperty("errorDes", e.getMessage());
		}
		
		return jsonObject.toString();
	}
		
	/**
	 * bundle文件上传
	 * @param name
	 * @param file
	 * @return
	 */
	@RequestMapping(value = "/bundleUpload", method=RequestMethod.POST, produces="text/plain")
    public String bundleUpload(@RequestParam("name") String name, @RequestParam("file") Part file){
		JsonObject result = new JsonObject();
		ParamSetting paramSettingServer = paramSettingReppository
				.findByParamName(Constants.SERVERMIX_SERVER);
		//TODO
		if(paramSettingServer==null){
			result.addProperty("backValue", false);
	        result.addProperty("errorDes", "上传服务器的ip地址未配置！");
	        return result.toString();
		}
		JsonArray jsonDatas = GsonUtil.getDefaultJsonParser()
				.parse(paramSettingServer.getParamValue()).getAsJsonArray();
		String fname = file.getSubmittedFileName();
		String fileName = "";
		if(fname.lastIndexOf("\\") != -1){
        	fileName = fname.substring(fname.lastIndexOf("\\") + 1, fname.length());
        }else{
        	fileName = fname;
        }
		for (JsonElement jsonElement : jsonDatas) {
			String ip = jsonElement.getAsJsonObject().get("ip").getAsString();
			String socketUploadPort = jsonElement.getAsJsonObject().get("SocketUploadPort").getAsString();
			if(!FileUploadCilent.uploadBundleBySocket(ip, socketUploadPort, fileName, file)){
				result.addProperty("backValue", false);
				result.addProperty("errorDes", "上传接口部署包到 【ip=" + ip + "】 这台服务器上失败！");
		        return result.toString();
			}
		}
		
		result.addProperty("backValue", true);
		result.addProperty("fileName", fileName);
		return result.toString();
		/*
		JsonObject result = new JsonObject();
		ParamSetting paramSettingServer = paramSettingReppository.findByParamName(Constants.SERVER_HANDLE_BUNDLE_PATH);
        JsonArray jsonDatas = GsonUtil.getDefaultJsonParser().parse(paramSettingServer.getParamValue()).getAsJsonArray();
        
        //测试上传地址是否存在
        for (JsonElement jsonElement : jsonDatas) {
        	String filePath = jsonElement.getAsJsonObject().get("uploadServer").getAsString();
        	File testFile = new File(filePath);
        	if(!testFile.exists()){
        		result.addProperty("backValue", false);
    	        result.addProperty("errorDes", "上传接口部署包的地址：" + filePath + " 不存在！");
    	        return result.toString();
        	}
        }
        String fname = file.getSubmittedFileName();
        String fileName = "";
        
        if(fname.lastIndexOf("\\") != -1){
        	fileName = fname.substring(fname.lastIndexOf("\\") + 1, fname.length());
        }else{
        	fileName = fname;
        }
        InputStream ios = null;
        FileOutputStream fos = null;
        try{
	        for (JsonElement jsonElement : jsonDatas) {
	        	File bundleFile = new File(jsonElement.getAsJsonObject().get("uploadServer").getAsString() + fileName);
	        	if(!bundleFile.exists()){
	        	}else{
	        		bundleFile.delete();
	        	}
	        	bundleFile.createNewFile();	
				ios = file.getInputStream();
					
				fos = new FileOutputStream(bundleFile);
				byte[] b = new byte[(int) file.getSize()];
				while((ios.read(b)) != -1){
					fos.write(b);
				}
				ios.close();
				fos.close();
			}
	        result.addProperty("backValue", true);
	        result.addProperty("fileName", fileName);
        } catch (Exception e) { 
        	e.printStackTrace();
        	result.addProperty("backValue", false);
        	result.addProperty("errorDes", e.getMessage());//保存错误信息
        } finally {
        	try {
				ios.close();
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
        }
        return result.toString();*/
	}
	
	
	
	@RequestMapping("/uploadFile")
	@ResponseBody
	public Map<String,Object> uploadFile(@RequestParam(value="Filedata")MultipartFile file, HttpServletRequest request){
        Map<String,Object> map=new HashMap<String, Object>();
        
        
        /*String proPath = ServiceManagerController.class.getClassLoader().getResource("").getPath();//得到当前项目的根目录的/bin:E:/eclipse/workspace/Cook-Test/bin/
		String filePath = proPath.substring(0, proPath.length() - 4);//得到当前项目的根目录:E:/eclipse/workspace/Cook-Test	
        File fileInput =new File(filePath + "bundleFile");
		if(!fileInput.exists()){
			fileInput.mkdirs();
		}*/
        /*String filePathServerFirst = Constants.SERVICEMIX_SERVIER_BUNDLE_PATH_1;
        String filePathServerTwo = Constants.SERVICEMIX_SERVIER_BUNDLE_PATH_2;*/
        //Long siez = file.getSize();
        //测试共享文件地址是否可以连通
		
        ParamSetting paramSettingServer = paramSettingReppository.findByParamName(Constants.SERVER_HANDLE_BUNDLE_PATH);
        JsonArray jsonDatas = GsonUtil.getDefaultJsonParser().parse(paramSettingServer.getParamValue()).getAsJsonArray();
        String fileName = file.getOriginalFilename();
        try{
	        for (JsonElement jsonElement : jsonDatas) {
	        	File bundleFile = new File(jsonElement.getAsJsonObject().get("uploadServer").getAsString() + fileName);
	        	/*if(!bundleFile.exists()){*/
	        		bundleFile.createNewFile();
					InputStream ios = file.getInputStream();
					
					FileOutputStream fos = new FileOutputStream(bundleFile);
					
					byte[] b = new byte[(int) file.getSize()];
					while((ios.read(b)) != -1){
						fos.write(b);
					}
					ios.close();
					fos.close();
				}
			/*}*/
	        map.put("success", true);
	        map.put("fileName", fileName);
        } catch (Exception e) { 
        	e.printStackTrace();
            map.put("success", false);
            map.put("fileName", fileName);
            map.put("msg", e.getMessage());//保存错误信息
        }
        return map;
 	}
	
	
	/**
     * 根据文件名删除bundle文件
     * @param fileName 文件名称
     * @param request
     * @return 返回结果信息
     *     
     */
    @RequestMapping("/deleteFile")
    @ResponseBody
    public Map<String,Object> deleteFile(String fileNames, HttpServletRequest request){
        Map<String,Object> map=new HashMap<String, Object>();
        
        /*String proPath = ServiceManagerController.class.getClassLoader().getResource("").getPath();//得到当前项目的根目录的/bin:E:/eclipse/workspace/Cook-Test/bin/
		String filePath = proPath.substring(0, proPath.length() - 4);//得到当前项目的根目录:E:/eclipse/workspace/Cook-Test
*/		
		
        /*String filePathFirst = Constants.SERVICEMIX_SERVIER_BUNDLE_PATH_1;
        String filePathTwo = Constants.SERVICEMIX_SERVIER_BUNDLE_PATH_2;*/
        System.out.println("开始删除");
        
        ParamSetting paramSettingServer = paramSettingReppository.findByParamName(Constants.SERVER_HANDLE_BUNDLE_PATH);
        JsonArray jsonDatas = GsonUtil.getDefaultJsonParser().parse(paramSettingServer.getParamValue()).getAsJsonArray();
        try{
	        if(fileNames.contains(",")){
		        String[] fileName = fileNames.split(",");
		        System.out.println("fileName:"+fileName[0]);
	        	for(int i = 0;i < fileName.length;i++){
	        		for (JsonElement jsonElement : jsonDatas) {
	        			File bundleFile = new File(jsonElement.getAsJsonObject().get("uploadServer").getAsString() + fileName[i]);
	        			if (bundleFile.exists()){
	        				bundleFile.delete();
				            map.put("success", true);
				            map.put("msg"," 删除成功");
				            System.out.println("删除成功");
				        }else{
				            map.put("success", false);
				            map.put("msg"," 删除失败,文件不存在或文件名错误!");
				            System.out.println("删除失败");
				        }
	        		}
	        	}
	        }else{
	        	for (JsonElement jsonElement : jsonDatas) {
        			File bundleFile = new File(jsonElement.getAsJsonObject().get("uploadServer").getAsString() + fileNames);
        			if (bundleFile.exists()){
        				bundleFile.delete();
			            map.put("success", true);
			            map.put("msg"," 删除成功");
			            System.out.println("删除成功");
			        }else{
			            map.put("success", false);
			            map.put("msg"," 删除失败,文件不存在或文件名错误!");
			            System.out.println("删除失败");
			        }
        		}
	        }
        }catch(Exception e){
        	e.printStackTrace();
        	map.put("success", false);
        }
        return map;
    }
    
    @RequestMapping(value = "/createFtpBluePrintFile", produces = "application/json")
	@Transactional
	public void createFtpBluePrintFile(String interfaceDatas, HttpServletResponse response) throws ParserConfigurationException, SAXException, IOException, TransformerException, ParseException {
    	
    	/*String proPath = ServiceManagerController.class.getClassLoader().getResource("").getPath();//得到当前项目的根目录的/bin:E:/eclipse/workspace/Cook-Test/bin/
		String filePath = proPath.substring(0, proPath.length() - 4);//得到当前项目的根目录:E:/eclipse/workspace/Cook-Test
    	String fileName = filePath + "blueprintFile/blueprint.xml";*/
    	
		InputStream fileName = resourceLoader.getResource("classpath:templates/blueprint.xml").getInputStream();
    	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    	dbf.setIgnoringElementContentWhitespace(true);
    	DocumentBuilder db = dbf.newDocumentBuilder();
    	Document xmldoc = db.parse(fileName);
    	
    	
    	Element root = xmldoc.getDocumentElement();
        
    	JsonObject jsonData = GsonUtil.getDefaultJsonParser().parse(interfaceDatas).getAsJsonObject();
    	
    	String runWay = jsonData.get("runWay").getAsString();// 执行周期单位(秒、分、时、天、周、月..)
    	String runCyc = jsonData.get("runCyc").getAsString();// 执行周期
    	Date beginTime = fastDateFormat1.parse(jsonData.get("beginTime").getAsString());
    	//Date endTime = fastDateFormat1.parse(jsonData.get("endTime").getAsString());
    	
    	String dayOfWeek = jsonData.get("dayOfWeek").getAsString();//周指定执行日
    	
    	String cron = "";
    	//周中的某天执行
    	if (StringUtils.equals(runCyc,"1") && StringUtils.equals(runWay, KettleJobScheduleCycleUnit.Day.ValueCode)) {
			Calendar beginTime2 = Calendar.getInstance();
			beginTime2.setTime(beginTime);
			int hour = beginTime2.get(Calendar.HOUR_OF_DAY);
			int minute = beginTime2.get(Calendar.MINUTE);
			
			Integer[] daysOfWeek = parseDaysOfWeek(dayOfWeek);
			cron = CornExpressionUtil.atHourAndMinuteOnGivenDaysOfWeek(hour, minute, daysOfWeek);
		} else {
			
			if(StringUtils.equals(runWay, KettleJobScheduleCycleUnit.Second.ValueCode)){
				//每隔几秒执行一次
				cron = "0/" + runCyc + " * * * * ?";
				
			}
			if(StringUtils.equals(runWay, KettleJobScheduleCycleUnit.Minute.ValueCode)){
				//每隔几分钟执行一次
				cron = "0 0/" + runCyc + " * * * ? *";
			}
			if(StringUtils.equals(runWay, KettleJobScheduleCycleUnit.Hour.ValueCode)){
				//每隔几小时执行一次
				cron = "0 0 0/" + runCyc + " * * ? *";
			}
			if(StringUtils.equals(runWay, KettleJobScheduleCycleUnit.Day.ValueCode)){
				//每隔几天执行一次
				cron = "0 0 0 1/" + runCyc + " * ? *";
			}
			if(StringUtils.equals(runWay, KettleJobScheduleCycleUnit.Week.ValueCode)){
				//每隔几周执行一次
				cron = "0 0 0 0 0 1#" + runCyc; 
			}
			if(StringUtils.equals(runWay, KettleJobScheduleCycleUnit.Month.ValueCode)){
				//每隔几月执行一次
				cron = "0 0 0 0 1/" + runCyc + " ? *";
			}
			
			
		}
    	
    	
    	String fileCachePath = jsonData.get("fileCachePath").getAsString();
    	
    	
    	String sources = "";
    	//源主机配置
    	JsonArray jsonArraySource = jsonData.get("sourceDatas").getAsJsonArray();
		for (int i = 0; i < jsonArraySource.size(); i++) {
			JsonObject jsonParmData = jsonArraySource.get(i).getAsJsonObject();
			String sourcePath = jsonParmData.get("sourceHost").getAsString();
			String source = "";
			if(sourcePath.indexOf("/") != -1){
				String sourceIp = sourcePath.substring(0, sourcePath.indexOf("/"));
				String path = sourcePath.substring(sourcePath.indexOf("/"), sourcePath.length());
				/*String source = jsonParmData.get("sourceHost").getAsString() + ":" + jsonParmData.get("sourceHostPort").getAsString();*/
				source = sourceIp + ":" + jsonParmData.get("sourceHostPort").getAsString() + path;
			}else{
				source = jsonParmData.get("sourceHost").getAsString() + ":" + jsonParmData.get("sourceHostPort").getAsString();
			}
			String sourceFileName = jsonParmData.get("sourceFileName").getAsString();
			Element from = xmldoc.createElement("from");
			String fromUrl = "";
			boolean isAnonymous = jsonParmData.get("sourceIsAnmous").getAsBoolean();
			if (isAnonymous) {
				fromUrl = "ftp://anonymous@" + source + "?binary=true&localWorkDirectory="+ fileCachePath + "&fileName=" + sourceFileName + "&scheduler=quartz2&scheduler.cron="+ cron;
			}else{
				String userName = jsonParmData.get("sourceUserName").getAsString();
				String password = jsonParmData.get("sourcePassword").getAsString();
				fromUrl = "ftp://" + userName + "@" + source + "?password="+ password + "&binary=true&localWorkDirectory="+ fileCachePath + "&fileName=" + sourceFileName + "&scheduler=quartz2&scheduler.cron="+ cron;
				
			}
	    	from.setAttribute("uri", fromUrl);
	    	root.getElementsByTagName("route").item(0).appendChild(from);
	    	
	    	if(source !="" && source != null){
	    		if(sources !="" && sources != null ){
	    			sources += "-";
	    		}
	    		sources += source;
	    	}
			
		}

		String interfaceCode = jsonData.get("interfaceCode").getAsString();
		//权限配置
		/*Element authBean = xmldoc.createElement("bean");
		authBean.setAttribute("ref", "authService");
		authBean.setAttribute("method", "authResult(" + interfaceCode + ")");
    	root.getElementsByTagName("route").item(0).appendChild(authBean);*/
    	
    	
    	//并行分发器配置
    	Element multicast = xmldoc.createElement("multicast");
    	root.getElementsByTagName("route").item(0).appendChild(multicast);
    	
    	/*String targets = "";*/
    	//目标主机配置
		JsonArray jsonArrayDes = jsonData.get("desDatas").getAsJsonArray();

		for (int i = 0; i < jsonArrayDes.size(); i++) {
			//串行管道连通后面的节点
	    	Element pipeline = xmldoc.createElement("pipeline");
	    	root.getElementsByTagName("multicast").item(0).appendChild(pipeline);
	    	
	    	
	    	
	    	
			JsonObject jsonParmData = jsonArrayDes.get(i).getAsJsonObject();
			String desPath = jsonParmData.get("desHost").getAsString();
			String des = "";
			if(desPath.indexOf("/") != -1){
				String desIp = desPath.substring(0, desPath.indexOf("/"));
				String path = desPath.substring(desPath.indexOf("/"), desPath.length());
				/*String source = jsonParmData.get("sourceHost").getAsString() + ":" + jsonParmData.get("sourceHostPort").getAsString();*/
				des = desIp + ":" + jsonParmData.get("desHostPort").getAsString() + path;
			}else{
				des = jsonParmData.get("desHost").getAsString() + ":" + jsonParmData.get("desHostPort").getAsString();
			}
			
			//权限配置
			Element authBean = xmldoc.createElement("bean");
			authBean.setAttribute("ref", "authService");
			authBean.setAttribute("method", "authResult(" + interfaceCode + ", " + sources + ", " + des + ", ${file:name}, ${file:length})");
			multicast.getElementsByTagName("pipeline").item(i).appendChild(authBean);
	    	
	    	
			Element to = xmldoc.createElement("to");
			String toUrl = "";
			boolean isAnonymous = jsonParmData.get("desIsAnmous").getAsBoolean();
			if (isAnonymous) {
				toUrl = "ftp://anonymous@" + des + "?binary=true";
			}else{
				String userName = jsonParmData.get("desUserName").getAsString();
				String password = jsonParmData.get("desPassword").getAsString();
				toUrl = "ftp://" + userName + "@" + des + "?password="+ password + "&binary=true";
				
			}
			
			to.setAttribute("uri", toUrl);
			multicast.getElementsByTagName("pipeline").item(i).appendChild(to);
	    	/*if(des !="" && des != null){
	    		if(targets !="" && targets != null ){
	    			targets += "-";
	    		}
	    		targets += des;
	    	}*/
	    	
	    	//camel控制台日志log
	    	Element camelLogBean = xmldoc.createElement("log");
	    	camelLogBean.setAttribute("message", "from " + sources + " to " + des + " 传输了${file:name}文件");
	    	multicast.getElementsByTagName("pipeline").item(i).appendChild(camelLogBean);
			
			
			//数据库日志配置
			Element logBean = xmldoc.createElement("bean");
			logBean.setAttribute("ref", "logService");
			logBean.setAttribute("method", "writeLog(" + interfaceCode + ", " + sources + ", " + des + ", ${file:name}, ${file:length})");
			multicast.getElementsByTagName("pipeline").item(i).appendChild(logBean);
		}
		
		
    	
    	//获取输出流
    	OutputStream out = response.getOutputStream();
    	response.reset();
    	response.setCharacterEncoding("UTF-8");
    	response.setHeader("Content-Disposition", "attachment;filename=blueprint.xml");
    	response.setContentType("application/octet-stream");
    	
    	//将生成的xml写入输出流
    	TransformerFactory factory = TransformerFactory.newInstance();
    	Transformer former = factory.newTransformer();
    	former.transform(new DOMSource(xmldoc), new StreamResult(out));
    	
    	out.flush();
    	out.close();
    	
    }
    
    
    private static Integer[] parseDaysOfWeek(String dayOfWeekStr){
		dayOfWeekStr = '[' + dayOfWeekStr + ']';
		return new Gson().fromJson(dayOfWeekStr, Integer[].class);
	}
    
    /**
     * 获取接口树形数据
     * @return
     */
    @RequestMapping(value = "/getBundlesForEasyUiTree", produces = "application/json")
    public String getBundlesForEasyUiTree(){
    	JsonObject jsonObject = new JsonObject();
    	BaseServiceManagementParam param = new BaseServiceManagementParam();
    	
    	List<Bundle> bundles = new ArrayList<Bundle>();
		try {
			bundles = serviceManagerService.getAllBundlesForTree(param);
		} catch (BundleActionException e) {
			e.printStackTrace();
			jsonObject.addProperty("backValue", false);
			jsonObject.addProperty("errorDes", "连接ServiceMix引擎失败！");
			return jsonObject.toString();
		}
    	
    	
    	Collator chineseCmp = Collator.getInstance(java.util.Locale.CHINA);
		Comparator<TreeNode> comparator = Comparator.comparing(TreeNode::getText, chineseCmp);
		
		// 组建树形对象，利用TreeSet进行排序
		TreeSet<TreeNode> bundleNodes = new TreeSet<>(comparator);
		bundles.forEach(bundle ->{
			String bundleId = String.valueOf(bundle.getId());
			String bundleName = bundle.getName();
			//String bundleVersion = bundle.getVersion();
			
			TreeNode bundleNode = CollectionUtils.find(bundleNodes, n -> StringUtils.equals(bundleId, n.getId()));
			if(bundleNode == null){
				bundleNode = new TreeNode();
				bundleNode.setNodeType("bundle");
				bundleNode.setId(bundleId);
				bundleNode.setText(bundleName);
				bundleNode.setChildren(new TreeSet<>(comparator));
				
				bundleNodes.add(bundleNode);
			}
			
		});
		
		return GsonUtil.getDefaultGson().toJson(bundleNodes);
    }
    
  //接口对比
  	@RequestMapping(value = "/compareInterface", produces = "application/json", method=RequestMethod.POST)
  	public String compareInterface(@RequestBody List<String> ids){
  		List<JsonObject> https = new ArrayList<JsonObject>();
  		for(String id:ids){
			try {
				JsonObject jsonObject = new JsonObject();
				Gson gs = new Gson();
				Http http = httpRepository.findOne(Http.idSpecification(id));
				if (http != null) {
					String fieldName=http.getFieldSystem().getFieldName();
					String systemName=http.getFieldSystem().getName();
					http.setFieldSystem(null);
					http.setInterfaceRequestQuantity(null);

					JsonArray IfParameterReqJsonDatas = new JsonArray();
					JsonArray IfParameterRepJsonDatas = new JsonArray();
					Set<IfParameter> interfaceParameterSet = http.getInterfaceParameter();
					for (IfParameter interfaceParameter : interfaceParameterSet) {
						interfaceParameter.setHttp(null);
						String paramType = interfaceParameter.getType();
						if(StringUtils.equals(paramType, ParameterType.REQUEST.ValueCode)){
							JsonObject jsonObjectParam = new JsonObject();
							jsonObjectParam.addProperty("paramId", interfaceParameter.getId());
							jsonObjectParam.addProperty("paramType", interfaceParameter.getType());
							jsonObjectParam.addProperty("paramName", interfaceParameter.getName());
							jsonObjectParam.addProperty("paramDataType", IfParameterType.get(interfaceParameter.getDataType()).ValueName);
							if(StringUtils.equals(interfaceParameter.getIsNeed(), "0")){
								jsonObjectParam.addProperty("isNeed", "否");
							}else{
								jsonObjectParam.addProperty("isNeed", "是");
							}
							jsonObjectParam.addProperty("paramDes", interfaceParameter.getDesc());
			
							IfParameterReqJsonDatas.add(jsonObjectParam);
						}else{
							JsonObject jsonObjectParam = new JsonObject();
							jsonObjectParam.addProperty("paramId", interfaceParameter.getId());
							jsonObjectParam.addProperty("paramType", interfaceParameter.getType());
							jsonObjectParam.addProperty("paramName", interfaceParameter.getName());
							jsonObjectParam.addProperty("paramDataType", IfParameterType.get(interfaceParameter.getDataType()).ValueName);
							if(StringUtils.equals(interfaceParameter.getIsNeed(), "0")){
								jsonObjectParam.addProperty("isNeed", "否");
							}else{
								jsonObjectParam.addProperty("isNeed", "是");
							}
							jsonObjectParam.addProperty("paramDes", interfaceParameter.getDesc());
			
							IfParameterRepJsonDatas.add(jsonObjectParam);
						}
					}
					http.setInterfaceParameter(null);

					http.setInterfaceToken(null);

					http.setDefinedbundles(null);

					http.setVisibleFieldSystems(null);

					jsonObject = GsonUtil.getDefaultJsonParser().parse(gs.toJson(http)).getAsJsonObject();
					jsonObject.add("IfParameterReqJsonDatas", IfParameterReqJsonDatas);
					jsonObject.add("IfParameterRepJsonDatas", IfParameterRepJsonDatas);
					jsonObject.addProperty("fieldName", fieldName);
					jsonObject.addProperty("systemName", systemName);
					
					

					https.add(jsonObject);
				} else {
					Ftp ftp = ftpRepository.findOne(Ftp.idSpecification(id));
					String fieldName=ftp.getFieldSystem().getFieldName();
					String systemName=ftp.getFieldSystem().getName();
					
					ftp.setFieldSystem(null);
					ftp.setDefinedbundles(null);
					ftp.setVisibleFieldSystems(null);
					
					
					JsonArray FtpJsonSourceDatas = new JsonArray();
					JsonArray FtpJsonDesDatas = new JsonArray();
					Set<FtpServer> FtpSet = ftp.getFtpServers();
					for (FtpServer ftpServer : FtpSet) {
						ftpServer.setFtp(null);
						if(StringUtils.equals(ftpServer.getHostType(), FtpHostType.SOURCE_HOST.ValueCode)){
							ftpServer.setFtp(null);
							ftpServer.setOwnFieldSystem(null);
							JsonObject jsonObjectParam = new JsonObject();
							jsonObjectParam.addProperty("host", ftpServer.getHost());
							jsonObjectParam.addProperty("port", ftpServer.getPort());
							if(StringUtils.equals(ftpServer.getIfAnonymous(), FtpAccessType.ANONYMOUS.ValueCode)){
								jsonObjectParam.addProperty("isAnonmous", "是");
							}else if(StringUtils.equals(ftpServer.getIfAnonymous(), FtpAccessType.UNANONYMOUS.ValueCode)){
								jsonObjectParam.addProperty("isAnonmous", "否");
							}
							
							if(StringUtils.equals(ftpServer.getIfDelSource(), FtpSourceFileHanderType.DELETE.ValueCode)){
								jsonObjectParam.addProperty("isDelSourceFile", "是");
							}else if(StringUtils.equals(ftpServer.getIfDelSource(), FtpAccessType.UNANONYMOUS.ValueCode)){
								jsonObjectParam.addProperty("isDelSourceFile", "否");
							}
							
							
							jsonObjectParam.addProperty("userName", ftpServer.getUserName());
							jsonObjectParam.addProperty("password", "******");
			
							FtpJsonSourceDatas.add(jsonObjectParam);
						}else if(StringUtils.equals(ftpServer.getHostType(), FtpHostType.TARGET_HOST.ValueCode)){
							ftpServer.setFtp(null);
							ftpServer.setOwnFieldSystem(null);
							JsonObject jsonObjectParam = new JsonObject();
							jsonObjectParam.addProperty("host", ftpServer.getHost());
							jsonObjectParam.addProperty("port", ftpServer.getPort());
							if(StringUtils.equals(ftpServer.getIfAnonymous(), FtpAccessType.ANONYMOUS.ValueCode)){
								jsonObjectParam.addProperty("isAnonmous", "是");
							}else if(StringUtils.equals(ftpServer.getIfAnonymous(), FtpAccessType.UNANONYMOUS.ValueCode)){
								jsonObjectParam.addProperty("isAnonmous", "否");
							}
							
							if(StringUtils.equals(ftpServer.getIfCover(), FtpTargetFileHanderType.COVER.ValueCode)){
								jsonObjectParam.addProperty("isCoverFile", "是");
							}else if(StringUtils.equals(ftpServer.getIfCover(), FtpTargetFileHanderType.UNCOVER.ValueCode)){
								jsonObjectParam.addProperty("isCoverFile", "否");
							}
							
							
							jsonObjectParam.addProperty("userName", ftpServer.getUserName());
							jsonObjectParam.addProperty("password", "******");
			
			
							FtpJsonDesDatas.add(jsonObjectParam);
						}
						
					}
					ftp.setFtpServers(null);
					ftp.setIfSchedules(null);
					jsonObject = GsonUtil.getDefaultJsonParser().parse(gs.toJson(ftp)).getAsJsonObject();
					jsonObject.add("FtpJsonSourceDatas", FtpJsonSourceDatas);
					jsonObject.add("FtpJsonDesDatas", FtpJsonDesDatas);
					jsonObject.addProperty("fieldName", fieldName);
					jsonObject.addProperty("systemName", systemName);
					
					
					
					https.add(jsonObject);
				}
			} catch (NoSuchObjectException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
  			;
  		}
  		return https.toString();
  	}
  	
  	/**
  	 * 测试ftp服务器是否可通
  	 * @param hostDatas
  	 * @return
  	 */
  	@RequestMapping(value="/testFtpServer", produces = "application/json", method=RequestMethod.POST)
  	public String testFtpServer(@RequestBody String hostDatas){
  		JsonObject jsonObject = new JsonObject();
  		try {
			ConnetServerTest.testFtpServerConnect(hostDatas);
			jsonObject.addProperty("backValue", true);
		} catch (ServerMixException e) {
			jsonObject.addProperty("backValue", false);
			jsonObject.addProperty("errorDes", e.getMessage());
		}
  		return jsonObject.toString();
  	}
  	
  	/**
  	 * 搜索匹配的接口
  	 * @param hostDatas
  	 * @return
  	 */
  	@RequestMapping(value="/findHttpInterfaceByIfName", produces = "application/json", method=RequestMethod.GET)
  	public String findHttpInterfaceByIfName(String ifName){
  		JsonObject jsonObject = new JsonObject();
  		if(StringUtils.isNotBlank(ifName)){
  			ifName = "%" + ifName + "%";
  		}
  		String systemNames = "";
  		List<String> httpDatas = httpRepository.findVagueByName(ifName);
  		for (String systemName : httpDatas) {
  			systemNames += ((StringUtils.isNotBlank(systemNames)==true?",":"") + systemName);
		}
  		if(!httpDatas.isEmpty()){
  			jsonObject.addProperty("backValue", true);
  			jsonObject.addProperty("httpDatas", systemNames);
  			return jsonObject.toString();
  		}
  		
  		jsonObject.addProperty("backValue", false);
  		return jsonObject.toString();
  	}
  	
  	
  	/**
  	 * 获取此接口的外部调用地址
  	 * @param interfaceCode
  	 * @param systemId
  	 * @param interfaceVersion
  	 * @return
  	 */
  	@RequestMapping(value="/getRequestAddress", produces = "application/json", method=RequestMethod.GET)
  	public String getRequestAddress(String interfaceCode, String systemId, String interfaceVersion){
  		FieldSystem system = fieldSystemRepository.findOne(FieldSystem.idSpecification(systemId));
  		String routePublishUrl = "http://" + FtpRouteHandleUtil.getLocalHost() + "/ftp/" + system.getCode() + "/" + interfaceVersion + "/" + interfaceCode;
  		JsonObject jsonObject = new JsonObject();
		jsonObject.addProperty("routePublishUrl", routePublishUrl);
  		return jsonObject.toString();
  	}
  	
  	
  	
  	/**
	 * 批量对接口注册发送邮件给管理员和接口管理员
	 * @param id
	 * @param interfaceType
	 * @return
	 */
	@RequestMapping(value="/batchSendIfRegisterEmail", produces="application/json")
	public String batchSendIfRegisterEmail(String httpIds, String ftpIds){
		List<HttpVo> httpVos = new ArrayList<HttpVo>();
		if(httpIds.contains(",")){
			//两个或两个以上
			String[] ids = httpIds.split(",");
			for (String id : ids) {
				Http http = httpRepository.findOne(Http.idSpecification(id));
				if(http != null){
					HttpVo httpVo = new HttpVo();
					BeanUtils.copyProperties(http, httpVo);
					httpVo.setFieldName(http.getFieldName());
					httpVo.setSystemName(http.getFieldSystemName());
					if(StringUtils.equals(http.getType(), IfType.WS.ValueCode)){
						httpVo.setType("WEBSERVICE");
					}else{
						httpVo.setType("REST");
					}
					httpVos.add(httpVo);
				}
			}
		}else{
			//只有一个
			Http http = httpRepository.findOne(Http.idSpecification(httpIds));
			if(http != null){
				HttpVo httpVo = new HttpVo();
				BeanUtils.copyProperties(http, httpVo);
				httpVo.setFieldName(http.getFieldName());
				httpVo.setSystemName(http.getFieldSystemName());
				if(StringUtils.equals(http.getType(), IfType.WS.ValueCode)){
					httpVo.setType("WEBSERVICE");
				}else{
					httpVo.setType("REST");
				}
				httpVos.add(httpVo);
			}
		}
		
		List<FtpVo> ftpVos = new ArrayList<FtpVo>();
		if(ftpIds.contains(",")){
			//两个或两个以上
			String[] ids = ftpIds.split(",");
			for (String id : ids) {
				Ftp ftp = ftpRepository.findOne(Ftp.idSpecification(id));
				if(ftp != null){
					FtpVo ftpVo = new FtpVo();
					BeanUtils.copyProperties(ftp, ftpVo);
					ftpVo.setFieldName(ftp.getFieldSystem().getFieldName());
					ftpVo.setSystemName(ftp.getFieldSystem().getName());
					ftpVo.setType("FTP");
					ftpVos.add(ftpVo);
				}
			}
		}else{
			//只有一个
			Ftp ftp = ftpRepository.findOne(Ftp.idSpecification(ftpIds));
			if(ftp != null){
				FtpVo ftpVo = new FtpVo();
				BeanUtils.copyProperties(ftp, ftpVo);
				ftpVo.setFieldName(ftp.getFieldSystem().getFieldName());
				ftpVo.setSystemName(ftp.getFieldSystem().getName());
				ftpVos.add(ftpVo);
			}
		}
		
		
		User user = userSessionService.getCurrentAuthenticatedUser();
		// 发送接口注册邮件
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userCode", user.getUserCode());

		map.put("httpVos", httpVos);
		map.put("ftpVos", ftpVos);
		
		User adminUser = userRepository.findByUserCode(Constants.FIXED_USER_CODE_FOR_ADMIN);
		map.put("emailAddress", adminUser.getEmailAddress());
		String requestIpAndPort = FtpRouteHandleUtil.getLocalHost();
		SimpleDateFormat DateTimeFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
		String time = DateTimeFormat.format(new Date()).replace(" ", "#");
		String requestUrl = "http://"+requestIpAndPort+"/pages/UserManagement/UserLogin.html?time=" + time;
		map.put("requestUrl", requestUrl);
		try {
			sendEmailService.CookSendEmail(map, Constants.USER_IFS_REGISTER_SUBJECT,
					Constants.USER_IFS_REGISTER_TEMPLATE);
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<User> ifAdminUserList = userRepository.findByRole_Id(Constants.FIXED_ROLE_ID_FOR_IF_ADMIN);
		for (int i = 0; i < ifAdminUserList.size(); i++) {
			if (StringUtils.isNotBlank(ifAdminUserList.get(i).getEmailAddress())) {
				map.put("emailAddress", ifAdminUserList.get(i).getEmailAddress());
				try {
					sendEmailService.CookSendEmail(map, Constants.USER_IFS_REGISTER_SUBJECT,
							Constants.USER_IFS_REGISTER_TEMPLATE);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		
		JsonObject jsonObject = new JsonObject();
		jsonObject .addProperty("backValue", true);
		return jsonObject.toString();
	}
	
	
	/**
	 * 服务发布http中根据查询条件获取所有的接口信息
	 * @param param 查询条件实体
	 * @param pageable	分页实体
	 * @return
	 */
	@RequestMapping("/search/findHttpInterfacesByUser")
	@RequiresPermissions(value={"businessServiceManagement:view", "businessServiceManagement:maintain"}, logical = Logical.OR)
	public Page<InterfaceVo> findHttpInterfacesByUser(HttpInterfaceParam param, Pageable pageable) {
		if(StringUtils.isNoneBlank(param.getName())){
			param.setName("%" + param.getName() + "%");
		}
		
		if(StringUtils.isNoneBlank(param.getCode())){
			param.setCode("%" + param.getCode() + "%");
		}
		
		if(StringUtils.isEmpty(param.getCreateTime())){
			param.setCreateTime(Constants.CREATE_DATE);
		}
		
		if(StringUtils.isEmpty(param.getEndTime())){
			param.setEndTime(Constants.END_DATE);
		}
		User user = userSessionService.getCurrentAuthenticatedUser();
		
		
		DefinedBundle definedBundleProxy = definedBundleRepository
				.findByBundleName(Constants.COOKPROXY_NAME);
		
		DefinedBundle definedBundleFtp = definedBundleRepository
				.findByBundleName(Constants.COOKFTP_NAME);
		
		//获取总的记录数
		BigInteger total = (BigInteger) httpRepository.countHttpInterfacesByUser(
							definedBundleProxy.getBundleCode(),
							user.getId(), 
							param.getFieldId(), 
							param.getFieldSystemId(),
							param.getName(),
							param.getCode(),
							param.getStatus(), 
							param.getAuditStatus(), 
							param.getCreateTime(), 
							param.getEndTime()).get(0);
		if (total == null || total.longValue() <= 0) {
			return new PageImpl<InterfaceVo>(
					new ArrayList<InterfaceVo>(0), pageable, 0);
		}
		
		//获取所有接口信息
		List<Object[]> interfaceDatas = httpRepository.findHttpInterfacesByUser(
							definedBundleProxy.getBundleCode(),
							user.getId(), 
							param.getFieldId(), 
							param.getFieldSystemId(),
							param.getName(),
							param.getCode(),
							param.getStatus(), 
							param.getAuditStatus(), 
							param.getCreateTime(), 
							param.getEndTime(), 
							pageable.getPageNumber()
							* pageable.getPageSize(), 
							pageable.getPageSize());
		
		List<InterfaceVo> result = new ArrayList<InterfaceVo>(interfaceDatas.size());
		for (Object[] object : interfaceDatas) {
			InterfaceVo interfaceVo = new InterfaceVo();
			
			interfaceVo.setInterfaceId(object[0] != null ? (String) object[0] : "");
			interfaceVo.setFieldId(object[1] != null ? (String) object[1] : "");
			interfaceVo.setFieldSystemId(object[2] != null ? (String) object[2] : "");
			interfaceVo.setFieldName(object[3] != null ? (String) object[3] : "");
			interfaceVo.setSystemName(object[4] != null ? (String) object[4] : "");
			interfaceVo.setInterfaceName(object[5] != null ? (String) object[5] : "");
			interfaceVo.setInterfaceCode(object[6] != null ? (String) object[6] : "");
			if(object[7] != null){
				if(StringUtils.equals((String) object[7], IfType.WS.ValueCode)){
					interfaceVo.setInterfaceType("WEBSERVICE");
				}else if(StringUtils.equals((String) object[7], IfType.REST.ValueCode)){
					interfaceVo.setInterfaceType("REST");
				}else if(StringUtils.equals((String) object[7], IfType.FTP.ValueCode)){
					interfaceVo.setInterfaceType("FTP");
				}else{
					interfaceVo.setInterfaceType("");
				}
			}else{
				interfaceVo.setInterfaceType("");
			}
			interfaceVo.setType(object[7] != null ? (String) object[7] : "");
			if(object[8] != null){
				if(StringUtils.equals((String) object[8], AuditStatusType.UNAUDITED.ValueCode)){
					interfaceVo.setAuditStatus("未审核");
				}else if(StringUtils.equals((String) object[8], AuditStatusType.AUDITED.ValueCode)){
					interfaceVo.setAuditStatus("已审核");
				}else{
					interfaceVo.setAuditStatus("");
				}
			}else{
				interfaceVo.setAuditStatus("");
			}
			
			interfaceVo.setCreatedDate(object[9] != null ? fastDateFormat1.format(object[9]) : "");
			interfaceVo.setInterfaceVersion(object[10] != null ? (String) object[10] : "");
			interfaceVo.setInterfaceDes(object[11] != null ? (String) object[11] : "");
			interfaceVo.setInterfaceStatus(object[12] != null ? (String) object[12] : "");
			interfaceVo.setBundleName(object[13] != null ? (String) object[13] : "");
			interfaceVo.setBundleType(object[14] != null ? (String) object[14] : "");
			result.add(interfaceVo);
		}
		Page<InterfaceVo> page = new PageImpl<InterfaceVo>(result,
				pageable, total.longValue());
		
		return page;
	}
	
	
	
	/**
	 * 服务发布http中根据查询条件获取所有的接口信息
	 * @param param 查询条件实体
	 * @param pageable	分页实体
	 * @return
	 */
	@RequestMapping("/search/findFtpInterfacesByUser")
	@RequiresPermissions(value={"businessServiceManagement:view", "businessServiceManagement:maintain"}, logical = Logical.OR)
	public Page<InterfaceVo> findFtpInterfacesByUser(HttpInterfaceParam param, Pageable pageable) {
		if(StringUtils.isNoneBlank(param.getName())){
			param.setName("%" + param.getName() + "%");
		}
		
		if(StringUtils.isNoneBlank(param.getCode())){
			param.setCode("%" + param.getCode() + "%");
		}
		
		if(StringUtils.isEmpty(param.getCreateTime())){
			param.setCreateTime(Constants.CREATE_DATE);
		}
		
		if(StringUtils.isEmpty(param.getEndTime())){
			param.setEndTime(Constants.END_DATE);
		}
		User user = userSessionService.getCurrentAuthenticatedUser();
		
		
		DefinedBundle definedBundleProxy = definedBundleRepository
				.findByBundleName(Constants.COOKPROXY_NAME);
		
		DefinedBundle definedBundleFtp = definedBundleRepository
				.findByBundleName(Constants.COOKFTP_NAME);
		
		//获取总的记录数
		BigInteger total = (BigInteger) httpRepository.countFtpInterfacesByUser(
							definedBundleFtp.getBundleCode(),
							user.getId(), 
							param.getFieldId(), 
							param.getFieldSystemId(),
							param.getName(),
							param.getCode(),
							param.getStatus(), 
							param.getAuditStatus(), 
							param.getCreateTime(), 
							param.getEndTime()).get(0);
		if (total == null || total.longValue() <= 0) {
			return new PageImpl<InterfaceVo>(
					new ArrayList<InterfaceVo>(0), pageable, 0);
		}
		
		//获取所有接口信息
		List<Object[]> interfaceDatas = httpRepository.findFtpInterfacesByUser(
							definedBundleFtp.getBundleCode(),
							user.getId(), 
							param.getFieldId(), 
							param.getFieldSystemId(),
							param.getName(),
							param.getCode(),
							param.getStatus(), 
							param.getAuditStatus(), 
							param.getCreateTime(), 
							param.getEndTime(), 
							pageable.getPageNumber()
							* pageable.getPageSize(), 
							pageable.getPageSize());
		
		List<InterfaceVo> result = new ArrayList<InterfaceVo>(interfaceDatas.size());
		for (Object[] object : interfaceDatas) {
			InterfaceVo interfaceVo = new InterfaceVo();
			
			interfaceVo.setInterfaceId(object[0] != null ? (String) object[0] : "");
			interfaceVo.setFieldId(object[1] != null ? (String) object[1] : "");
			interfaceVo.setFieldSystemId(object[2] != null ? (String) object[2] : "");
			interfaceVo.setFieldName(object[3] != null ? (String) object[3] : "");
			interfaceVo.setSystemName(object[4] != null ? (String) object[4] : "");
			interfaceVo.setInterfaceName(object[5] != null ? (String) object[5] : "");
			interfaceVo.setInterfaceCode(object[6] != null ? (String) object[6] : "");
			if(object[7] != null){
				if(StringUtils.equals((String) object[7], IfType.WS.ValueCode)){
					interfaceVo.setInterfaceType("WEBSERVICE");
				}else if(StringUtils.equals((String) object[7], IfType.REST.ValueCode)){
					interfaceVo.setInterfaceType("REST");
				}else if(StringUtils.equals((String) object[7], IfType.FTP.ValueCode)){
					interfaceVo.setInterfaceType("FTP");
				}else{
					interfaceVo.setInterfaceType("");
				}
			}else{
				interfaceVo.setInterfaceType("");
			}
			interfaceVo.setType(object[7] != null ? (String) object[7] : "");
			if(object[8] != null){
				if(StringUtils.equals((String) object[8], AuditStatusType.UNAUDITED.ValueCode)){
					interfaceVo.setAuditStatus("未审核");
				}else if(StringUtils.equals((String) object[8], AuditStatusType.AUDITED.ValueCode)){
					interfaceVo.setAuditStatus("已审核");
				}else{
					interfaceVo.setAuditStatus("");
				}
			}else{
				interfaceVo.setAuditStatus("");
			}
			
			interfaceVo.setCreatedDate(object[9] != null ? fastDateFormat1.format(object[9]) : "");
			interfaceVo.setInterfaceVersion(object[10] != null ? (String) object[10] : "");
			interfaceVo.setInterfaceDes(object[11] != null ? (String) object[11] : "");
			interfaceVo.setInterfaceStatus(object[12] != null ? (String) object[12] : "");
			interfaceVo.setBundleName(object[13] != null ? (String) object[13] : "");
			interfaceVo.setBundleType(object[14] != null ? (String) object[14] : "");
			result.add(interfaceVo);
		}
		Page<InterfaceVo> page = new PageImpl<InterfaceVo>(result,
				pageable, total.longValue());
		
		return page;
	}
    
}
